Home > Article > Web Front-end > How can I Fetch Data Efficiently in Next.js 13 to Avoid Undefined Data?
Next.js offers several methods for server-side data fetching, including getStaticProps and getServerSideProps. However, these methods are primarily intended for page components within the pages folder. In Next.js 13, a new concept known as Server Components emerged, allowing for data fetching directly within the component body.
Server Components provide a more flexible approach to data fetching, enabling developers to:
To utilize Server Components, define your component as the default export of a file in the app directory. Data fetching can be performed within the component body using the following methods:
import { headers, cookies } from "next/headers"; export default async function Component({ params, searchParams }) { // Cached until manually invalidated const staticData = await fetch(`https://...`, { cache: "force-cache" }); // Refetched on every request const dynamicData = await fetch(`https://...`, { cache: "no-store" }); // Revalidated with a 10-second lifetime const revalidatedData = await fetch(`https://...`, { next: { revalidate: 10 } }); }
In addition to Server Components, you can also fetch data using libraries or directly interact with a database using an ORM. In such scenarios, you can leverage Route Segment Config:
// layout.js OR page.js OR route.js import prisma from "./lib/prisma"; // Caching options export const revalidate = 10; // Revalidate every 10s // OR export const dynamic = "force-dynamic"; // No caching async function getPosts() { const posts = await prisma.post.findMany(); return posts; } export default async function Page() { const posts = await getPosts(); }
By utilizing Server Components or alternative approaches, you can efficiently fetch data on the server in Next.js, addressing the issue of undefined data encountered when relying solely on getStaticProps.
The above is the detailed content of How can I Fetch Data Efficiently in Next.js 13 to Avoid Undefined Data?. For more information, please follow other related articles on the PHP Chinese website!