next.js - getInitialProps does not work in component

Viewed 2979

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?

2 Answers

getInitialProps can only be added to the default component exported by a page, adding it to any other component won't work.

Related