Reputation: 119
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.
Upvotes: 1
Views: 2202
Reputation: 2261
From the Next.js docs:
Note: getInitialProps can not be used in children components. Only in pages.
Upvotes: 2