Next.js: Child components and getInitialProps()

Created on 25 May 2017  Â·  1Comment  Â·  Source: vercel/next.js

I realize this issue has been discussed quite a bit in #192, except that issue seemed to focus on HOC (higher-order-components). I _think_ I have a slightly different scenario... maybe...

I want to design a component that has the following responsibility:

  • Fetch and display a list of articles, showing the following data about each: Title, author, image, url, summary.
  • Allow the consumer to specify a data source (eg articles, blog posts) and filter properties (eg items less than 30 days old). There is no user-interactivity here in the sense of changing the data source or filters; they just need to be configured by the developer.
  • The data will come from one of several REST API's, depending on the data source parameter.
  • This is probably a very common component on many publishing websites, used to display “What’s new” or “Other articles related to the one you’re reading” type of lists.
  • I want to be able to use this component on many pages, and be able to use it multiple times per page

I want to be able to use the component (named ContentFeed) on a page like this:

const Index = () => (
  <MyLayout>
    <div> This will be a list of articles:
      <ContentFeed dataSource={'articles'} filter={date: 'last 30d'}/>
    </div>
    <div>... some stuff specific to this page ...</div>
    <div> This will be a list of blog posts:
      <ContentFeed dataSource={'blogs'} filter={author: 'Joe'}/>
    </div>
  </MyLayout>
)

The key is that I want the ContentFeed component to handle fetching all it's own data (server-side for SEO reasons) because I want to encapsulate the knowledge of how to interpret the data source and filter parameters within that component. The fact that getInitialProps() only works on page-level components prevents me from using this inside ContentFeed to fetch the data, so I'm not sure how to approach this.

However, I feel like I might be misunderstanding a design principle around react. Is there better way to approach this?

>All comments

As we said in that #192
We don't have plans to add support for calling getInitialProps in nested components.

Learn about using Redux or similar.
May be you can try something like async-reactor: https://www.npmjs.com/package/async-reactor

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pie6k picture pie6k  Â·  3Comments

swrdfish picture swrdfish  Â·  3Comments

jesselee34 picture jesselee34  Â·  3Comments

flybayer picture flybayer  Â·  3Comments

formula349 picture formula349  Â·  3Comments