Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When override _app.js what is getInitialProps used for?

Tags:

next.js

what is this really do ?

pageProps = await Component.getInitialProps(ctx)

it looks "pageProps" this is just an empty object

import App, {Container} from 'next/app'
import React from 'react'

export default class MyApp extends App {
  static async getInitialProps ({ Component, router, ctx }) {
    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return {pageProps}
  }

  render () {
    const {Component, pageProps} = this.props
    return <Container>
      <Component {...pageProps} />
    </Container>
  }
}
like image 509
crapthings Avatar asked Sep 06 '18 01:09

crapthings


People also ask

What does getInitialProps do?

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.

Is getInitialProps deprecated?

Addition of getServerSideProp and getServerSideProp is greatly desirable, since getInitialProps will be deprecated and most likely deleted from next. js .

Can you use getServerSideProps in _APP js?

getServerSideProps does not work in _app. js . see docs. you could use the older getInitialProps in your custom app component but then the automatic static optimisation is disabled, which is something Next.


1 Answers

getInitialProps allows you to call out to get the props that you would like the component to have when rendered on the server.

For instance, I might need to display the current weather and I want Google to index my pages with that information for SEO purposes.

To achieve that, you'd do something like this:

import React from 'react'
import 'isomorphic-fetch'
const HomePage = (props) => (
  <div>
    Weather today is: {weather}
  </div>
)
HomePage.getInitialProps = async ({ req }) => {
  const res = await fetch('https://my.weather.api/london/today')
  const json = await res.json()
  return { weather: json.today }
}
export default HomePage 

The line pageProps = await Component.getInitialProps(ctx) calls that initial function so that the HomePage component is instantiated with the initial props that result from that call to the weather API.

like image 152
stef Avatar answered Sep 25 '22 06:09

stef