Home >Web Front-end >JS Tutorial >Why Isn't `getStaticProps` Running and Returning Undefined in the Latest Next.js App Directory?
When attempting to fetch data from an API endpoint using getStaticProps in the latest version of Next.js, users encounter the issue where the function does not execute and the returned data is undefined. This results in an error when mapping the data since it cannot read properties of undefined.
While getStaticProps is used to fetch data on the server, it is only applicable to page components within the pages folder, which is the traditional method of setting up routes in Next.js.
In modern Next.js applications using the app directory, server components provide a more flexible approach to data fetching. Here's a code snippet that demonstrates how to fetch data directly in the component body:
import { cookies, headers } from "next/headers"; export default async function Component({ params, searchParams }) { const staticData = await fetch("https://...", { cache: "force-cache" }); const dynamicData = await fetch("https://...", { cache: "no-store" }); const revalidatedData = await fetch("https://...", { next: { revalidate: 10 } }); return "..."; }
This code allows you to control the caching behavior of the fetched data, including forced caching, no caching, or revalidation after a specified period.
Alternatively, you can also fetch data without using fetch(); use third-party libraries or directly query your database with an ORM. In this case, you can use Route Segment Config:
async function getPosts() { const posts = await prisma.post.findMany(); return posts; } export default async function Page() { const posts = await getPosts(); // ... }
This approach enables you to specify the caching behavior of the fetched data through the revalidate property or disable caching altogether using the dynamic property.
The above is the detailed content of Why Isn't `getStaticProps` Running and Returning Undefined in the Latest Next.js App Directory?. For more information, please follow other related articles on the PHP Chinese website!