Reputation: 8635
Here's my code
import React from 'react'
import fetch from 'isomorphic-unfetch'
import Book from './Book'
function getNum(val) {
val = +val || 0;
return val;
}
class BookList extends React.Component {
static async getInitialProps(ctx) {;
const res = await fetch('/api/books');
const json = await res.json();
return { books: json }
}
render() {
var books = this.props.books;
For some reason "books" in the render function is undefined. Why doesn't getInitialProps work in a component?
Upvotes: 2
Views: 4360
Reputation: 291
getInitialProps
works only at pages level, not at components level.
sgetInitialProps can not be used in children components, only in the default export of every page
https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#caveats
Upvotes: 3
Reputation: 2976
getInitialProps
can only be added to the default component exported by a page, adding it to any other component won't work.
Upvotes: 4