How to fetch data in Nextjs 13 appDir

How to fetch data in Next 13 app route


Nextjs 13 comes with lots of experimental features, one of them was the appDir. Let’s talk about the data fetching in Nextjs 13.

In the older version we have fetched data in Next app with static props function and passes it down to component as props.

Things have been changed a lot. In appDir data fetching is done at server side and will be available to client. It also improvises the performance.

Do you know that, in Next 13 we can create client and server components. ?

GetData

Define a getData function at the route (page.jsx) and use it in the home component as follows



async function getData() {

  const res = await client.fetch(
    `*[_type == "post"]{title,_createdAt,slug,_id,summary,featured_image} | order(_createdAt desc)`
  );
  const data = await res;
  return data;
}

export default async function Home() {
 
  const posts = await getData();    

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.