67
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.jsでデータを取得する 〜getInitialProps〜

Last updated at Posted at 2019-02-16

:bangbang: 2020.05 Next.js 9.3から、データ取得用の新しいメソッド(getServerSidePropsなど)が推奨になりました。新しいコードをgetInitialPropsで書く理由はありません https://qiita.com/matamatanot/items/1735984f40540b8bdf91 


Next.jsでページロード前に必要なデータをfetchするには、getInitialPropsを利用しますが、ちょっと引数が複雑だったのでメモ。

以下、概ね↓の和訳です。
https://nextjs.org/docs/#fetching-data-and-component-lifecycle

データのfetchとコンポーネントライフサイクル

state,ライフサイクルhook,初期データが必要なときは、SFCの代わりにReact.Componentをexportします。

import React from 'react'

class HelloUA extends React.Component {
  static async getInitialProps({ req }) {
    const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
    return { userAgent }
  }

  render() {
    return (
      <div>
        Hello World {this.props.userAgent}
      </div>
    )
  }
}

export default HelloUA

ページロード時にデータを取得するには、getInitialPropsという非同期で静的なメソッドを使います。このメソッドは、JavaScriptの単純なObjectなら何でも非同期に取得でき、返り値はpropsに注入されます。
getInitialPropsから返されたデータは、サーバー側のレンダリング時にJSON.stringifyがするのと似た形でシリアライズされます。Date,Map,Setを扱うことはできないのでご注意ください。

最初のページロード時には、getInitialPropsはサーバー側でのみ実行されます。クライアントサイドで実行されるのは、別のルートからLinkコンポーネントまたはルーティングAPIで移動してきたときだけです。

getInitialPropsは子コンポーネントでは利用できません。pagesのみです。

getInitialPropsをステートレスなコンポーネントで使うこともできます。

function Page({ stars }) {
  return <div>Next stars: {stars}</div>
}

Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  return { stars: json.stargazers_count }
}

export default Page

getInitialPropsは以下のプロパティを持つオブジェクトを引数として受け取っています。

  • pathname - URLのパス部分
  • query - URLのクエリ部分をパースしたオブジェクト
  • asPath - ブラウザに実際に表示されているパス+クエリの文字列
  • req - HTTPリクエストオブジェクト(サーバーサイドのみ)
  • res - HTTPレスポンスオブジェクト(サーバーサイドのみ)
  • jsonPageRes - Fetch Responseオブジェクト(クライアントサイドのみ)
  • err - レンダー中にエラーが起きた場合のエラーオブジェクト
67
56
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?