How to fetch data

This page will walk you through how you can fetch data in Server Componentsarrow-up-right and Client Componentsarrow-up-right. As well as how to streamarrow-up-right content that depends on data.

Here is a tutorial on how to fetch data. This entire documentation is referenced from Nextjs, so for a better overview, please check this tutorial from Nextjs - https://nextjs.org/docs/app/getting-started/fetching-dataarrow-up-right

You can fetch data in Server Components using:

With the fetch APIarrow-up-right

To fetch data with the fetch API, turn your component into an asynchronous function, and await the fetch call.

For example:

app/blog/page.tsx

export default async function Page() {
  const data = await fetch('https://api.vercel.app/blog')
  const posts = await data.json()
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  )
}

With an ORM or databasearrow-up-right

Since Server Components are rendered on the server, you can safely make database queries using an ORM or database client. Turn your component into an asynchronous function, and await the call:

app/blog/page.tsx

There are two ways to fetch data in Client Components, using:

  1. A community library like SWRarrow-up-right or React Queryarrow-up-right

With the use hookarrow-up-right

You can use React's use hookarrow-up-right to streamarrow-up-right data from the server to client. Start by fetching data in your Server component, and pass the promise to your Client Component as prop:

app/blog/page.tsx

Then, in your Client Component, use the use hook to read the promise:

app/ui/posts.tsx

In the example above, you need to wrap the <Posts /> component in a <Suspense> boundaryarrow-up-right. This means the fallback will be shown while the promise is being resolved. Learn more about streamingarrow-up-right.

Community librariesarrow-up-right

You can use a community library like SWRarrow-up-right or React Queryarrow-up-right to fetch data in Client Components. These libraries have their own semantics for caching, streaming, and other features. For example, with SWR:

app/blog/page.tsx

Last updated

Was this helpful?