Next.js: how should sub-components get data they need?

Created on 21 Dec 2017  路  8Comments  路  Source: vercel/next.js

If I have a page, with numerous sub components such as a Header that displays some account info, how do I best get the data for that component?

If i use componentDidMount and do a request to my laravel api, then there is a delay where the data should be until its loaded.

If I use getInitialProps then I have to have a endpoint for every page to get these details and then always have to pass it down.

Is there any other solutions that dont cause these 2 issues?

Most helpful comment

Hmm i see, all methods quite tedious. What have been nice to someway allow getInitialProps on any component and all calls are batched on the server. That way each component can control itself.

All 8 comments

My recommendation is to use getInitialProps since it will let you fetch data client and server side, not only client side as componentDidMount.

If you want to fetch the same data in many pages (you use the same subcomponent) what you can do is create a HOC for that common data and apply it to your pages so they will all fetch it and you don't need to copy the same code on each page.

If you want to avoid doing many HTTP request or creating a custom endpoint per page you can take a look at GraphQL since it was done to avoid that exact issue.

Hmm i see, all methods quite tedious. What have been nice to someway allow getInitialProps on any component and all calls are batched on the server. That way each component can control itself.

You can do that with GraphQL's Apollo, which let you define what data you need on each component and then fetch it when doing the render.

Creating a higher order component is the way to go when you鈥檙e not using Apollo. Apollo allows data fetch on per component basis

But with that there is always a delay between the page loading and the content loading

No, the page is not going to render until the code of getInitialProps finish, so is going to wait for your data to arrive before rendering.

So I could have a HOC that has getInitialProps that wraps a page that also has getInitialProps?

Exactly, check the examples, we have one with high order components

Was this page helpful?
0 / 5 - 0 ratings