NextJs server components return empty array from Json Server

22 Views Asked by At
**api/tempaltes**
 `    export async function GET(request: Request) {

const res = await fetch("http://localhost:3000/templates"); const data = await res.json();

return Response.json({ data }); }`

**Page.tsx**
`async function getTemplates() {
const res = await fetch("http://localhost:3001/api/templates");
// The return value is *not* serialized
// You can return Date, Map, Set, etc.

if (!res.ok) {
  // This will activate the closest `error.js` Error Boundary
  throw new Error("Failed to fetch data");
}

return res.json();
}`




`
 export default async function Home() {
   const data = await getTemplates();
 console.log(data); // return []

  return <div>Tempaltes</div>;
 }

`

db.json { "templates": [ { "id": 1, "name": "Test" } ] }

When using server components in NextJS data fetching doesn't work. (through Server Actions and and Route Handlers) But when switching to client components, everything just fine. (useEffect)

Data creation works properly.

0

There are 0 best solutions below