Chris Hansen
Chris Hansen

Reputation: 8635

next.js - getInitialProps does not work in component

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

Answers (2)

eroll.maxhuni
eroll.maxhuni

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

ddon-90
ddon-90

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

Related Questions