1
votes

I'm working on converting my CRA to a SSR app using Next.js. I've just started and already running into a simple problem(i hope). I am able to render data to the browser directly from my index.js page using getInitialProps(). I obviously y don't want to set up my entire app on my index page though.

The problem I am having is trying to import data from a child component to the index page. Using the same code as my working example, I get the dreaded "TypeError: Cannot read property 'map' of undefined" error. Is this simple export/import setup not doable in React.

Here is an example similar to my code, in a child component...

import Link from 'next/link'
import 'isomorphic-unfetch'

export default class Index extends React.Component {
  static async getInitialProps () {
    // eslint-disable-next-line no-undef
    const res = await fetch('https://api.github.com/repos/zeit/next.js')
    const json = await res.json()
    return { stars: json.stargazers_count }
  }

  render () {
    return (
      <div>
        <p>Next.js has {this.props.stars} ⭐️</p>
        <Link prefetch href='/preact'>
          <a>How about preact?</a>
        </Link>
      </div>
    )
  }
}

So I then Import that component into my Index...

import React from 'react'
import App from '../components/App.js';

export default class Index extends React.Component {

  render () {
    return (
      <div>
         <App />
      </div>
    )
  }
}

So again, the child component works as a standalone Parent, but not as a child. Getting the error .map is not defined.

1
Well looks like getInitialProps does not work in Child components... What would be the correct way of making a SSR call from a child component? This answer may be on the google machine already, but can't find a direct answer. - Denis J
Why would you fetch remote data during SSR in the first place? All you really need is your basic page structure for the initial render, you can very well populate the data on the client side, using either hooks or traditional lifecycle methods. You shouldn't be using getInitialProps at all here. - Thomas Hennes

1 Answers

2
votes

From the Next.js docs:

Note: getInitialProps can not be used in children components. Only in pages.