Next.js Discord

Discord Forum

fetch data from API on component

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hello Everyone, I'm new on NextJS

A question, how to fetch the data from API into component??
I'm using Pages Router on NextJS 14, the component itself is a <Nav /> component inside a <Header /> component, I know we can useEffect for this, but I want it's render on server side for SEO purposes, based on documentation, for fetching data on server side we can use getStaticProps or getServerSideProps, but it's only be able executed on page, and I don't think pass the API result as a prop from every page into <Nav /> component using Lifting State Up is the best approach.

I really appreciate about the help, thanks.

6 Replies

@Ray you could use react context if you don't want to pass the data as props. or use react-query and prefetch the query on server https://tanstack.com/query/latest/docs/framework/react/guides/ssr#full-nextjs-pages-router-example
Sun bearOP
Hello Ray, nice to meet you again here
I've take a look on react-query, but just to make sure is there another best approach (or Nextjs native method) to pre-fetch the data in partial components
I'll try this one and will mark your answer if that works, thank you mate 😁
@Ray the next way for page router is, fetch the data in getServerSideProps and pass the data down to component
Sun bearOP
so, in my case is using Lifting State up right?
because the <Nav /> is inside a <Header />