Next.js: Example of async getInitialProps with functional component

Created on 24 Mar 2017  路  5Comments  路  Source: vercel/next.js

readme.md

When you need state, lifecycle hooks or initial data population you can export a React.Component (instead of a stateless function, like shown above):

import React from 'react'
export default class extends React.Component {
  static async getInitialProps ({ req }) {
    return req
      ? { userAgent: req.headers['user-agent'] }
      : { userAgent: navigator.userAgent }
  }
  render () {
    return <div>
      Hello World {this.props.userAgent}
    </div>
  }
}

You may use also functional component:

import React from 'react'
import 'isomorphic-fetch'
const Page = (props) => (
  <div>
    Preact stars: {props.stars}
  </div>
)
Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/developit/preact')
  const json = await res.json()
  return { stars: json.stargazers_count }
}
export default Page

Most helpful comment

A simple example returning a promise might be useful too?

import 'isomorphic-fetch'

const Page = ({ name, stargazers_count }) => (
  <div>
    {name} stars: {stargazers_count}
  </div>
)

Page.getInitialProps = () => {
  return fetch('https://api.github.com/repos/developit/preact')
    .then(res => res.json())
}

Page.propTypes = {
  name: PropTypes.string.isRequired,
  stargazers_count: PropTypes.number.isRequired
}

export default Page

All 5 comments

I think this is super useful info for our users. @rauchg ?

yuuuup. Let's add it!

A simple example returning a promise might be useful too?

import 'isomorphic-fetch'

const Page = ({ name, stargazers_count }) => (
  <div>
    {name} stars: {stargazers_count}
  </div>
)

Page.getInitialProps = () => {
  return fetch('https://api.github.com/repos/developit/preact')
    .then(res => res.json())
}

Page.propTypes = {
  name: PropTypes.string.isRequired,
  stargazers_count: PropTypes.number.isRequired
}

export default Page

How can I use multiple api in single page.

For example, my News website Left side has Latest news, and Right side has Popular news & Category wise 5 news. so how can I use multiple api's.

_I had learned this code from : https://nextjs.org/learn/basics/fetching-data-for-pages/fetching-data-for-pages_

Sample code is attaching here.

import Layout from '../comps/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'
import Head from 'next/head'

const Index = (props) => (
  <Layout>
<h1>Batman TV Shows</h1>
    <div>
      {props.shows.map(({show}) => (
        <div key={show.id}>
          <Link as={`p/${show.id}`} href={`/post?id=${show.id}`}>
        <div className="media">
            <div className="media-body">
            <a href="">
            <h4 className="media-heading">{show.name}</h4>
            </a>
            <div>{show.summary}</div>
        </div>
        </div>
          </Link>
    <br/>
        </div>
      ))}
    </div>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
  const data = await res.json()

  console.log(`Show data fetched. Count: ${data.length}`)

  return {
    shows: data
  }
}

export default Index

Now I implemented these things in my news website, Now I want 2 dynamic things in 1 page,
Left side has Latest news, and Right side has Popular news & Category wise 5 news.

Kindly give me solution. thanks in advance :bowing_man: :+1: :fireworks:

@shurvirmori Hey you must be new here, welcome. This place is for Next.js issues, not support. You wont find help here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DvirSh picture DvirSh  路  3Comments

irrigator picture irrigator  路  3Comments

havefive picture havefive  路  3Comments

sospedra picture sospedra  路  3Comments

jesselee34 picture jesselee34  路  3Comments