Zhassulan Nurushev
Zhassulan Nurushev

Reputation: 133

How to get initial data from api before app loaded in next.js

I want to load some data from api before application rendered.

Yes, I know we can do it in getInitialProps method of component, but I don't want load it on each component loading, I need make only 1 api call and make accessible retrieved data among all components. What is the easiest way to do it?

Upvotes: 3

Views: 4420

Answers (1)

Andrew Bass
Andrew Bass

Reputation: 346

Yes, I know we can do it in getInitialProps method of component

I think this may be where your confusion is coming from. The getInitialProps method is for page loads. Not for individual component loads.

I need make only 1 api call and make accessible retrieved data among all components.

There are a couple of ways to do this.

If you want to take advantage of SSR

Use getInitalProps for the page load and then pass the props down into sub components as you would in normal react application.

If you just want to stick to React

Make a higher level component that contains all of the sub components that need the api data. Call the api in the ComponentDidMount method or you could use React Hooks. From the higher level component again pass the data via props as you would in a normal react application.

Either way you are limiting the number of times you make the api call. That way you aren't hitting the endpoint each time the DOM re-renders each and every component.

Both the Next.js Learn and React Docs are excellent - I'm there all the time!

Upvotes: 1

Related Questions