Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js React component getInitialProps doesn't bind props

In Next.js, you can use in your React components a lifecycle method bound to the server side rendering on first load.

I tried to use this function as presented in the ZEIT tutorial (alternatively on their Github), but this.props doesn't seem to get JSON returned by the function. When I click on the component, console print an empty object.

import React from 'react'
import 'isomorphic-fetch'
export default class extends React.Component {
    static async getInitialProps () {
        const res = await fetch('https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json')
        const data = await res.json()
        return { data }
    }
    print() {
        console.log(this.props);
    }
    render() {
        return <div onClick={this.print.bind(this)}>print props</div>
    }
}
like image 844
imrok Avatar asked Nov 30 '16 13:11

imrok


People also ask

Is getInitialProps deprecated?

getInitialProps is not deprecated. But we do not recommend its usage over getStaticProps or getServerSideProps .

What is getInitialProps in NextJS?

getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. getInitialProps will disable Automatic Static Optimization.

Does getInitialProps run on client side?

With getInitialProps , the transition will execute server-side on the initial page load, but then execute on the client during page transitions.

Can you use react components in next JS?

Next. js has built-in support for CSS, Sass and CSS-in-JS. With Create React App, you can import . css files directly inside React components.


1 Answers

I had this issue due to a problem in my _app.js (i.e. NextJS Custom App) which I caused while adding in Redux (not a Redux issue). As soon as I started using getInitialProps in a page my props were empty at render though data was there in the static call. The cause was the incorrect propagation of pageProps in my _app.js.

So in my case the fix was changing, in custom _app.js getInitialProps, this:

return {
  ...pageProps,
  initialReduxState: reduxStore.getState()
}

to:

return {
  pageProps: {...pageProps},
  initialReduxState: reduxStore.getState()
}

.. so the render method as seen in the NextJS doc link could wire them through.

like image 138
user10023673 Avatar answered Oct 24 '22 08:10

user10023673