LoginSignup
6
7

More than 3 years have passed since last update.

【Gatsby.js】jsonファイルのデータをGraphQL経由で取得する

Posted at

この記事ではjsonファイルからGraphQL経由でデータを取得し、ページ内で利用する方法を紹介します。

jsonファイルを元に、複数ページを生成する方法を知りたい場合は昨日書いた以下の記事を参照。
【Gatsby.js】単一のjsonファイルを元に複数のページを生成する - Qiita

jsonファイルを配置

$ mkdir src/data
$ touch src/data/events.json
src/data/events.json
[
  {
    "title": "Gatsby勉強会",
    "date": "2020/10/01"
  },
  {
    "title": "React勉強会",
    "date": "2020/11/01"
  },
  {
    "title": "JavaScript勉強会",
    "date": "2020/12/01"
  }
]

プラグインをインストール

$ yarn add gatsby-transformer-json gatsby-source-filesystem
gatsby-config.js
module.exports = {
  plugins: [
    `other-plugin-hoge`,
    //追記↓
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/data/`,
      },
    },
  ],
}

クエリを作成

gatsby developで開発サーバーを起動し、http://localhost:8000/___graphql?query にアクセスしGraphiQLを開く。
まずはroot?にallEventsJsonという項目が追加されていることを確認。

allEventJson > edges > nodeを開き、titledateにチェックを入れてクエリを発行。

データを使いたいページ内で、データを取得

ここではsrc/pages/events.jsというページでデータを利用します。

$ touch src/pages/events.js
src/pages/events.js
import React from "react"
import { graphql, useStaticQuery } from "gatsby"

export default () => {
  const data = useStaticQuery(graphql`
    query {
      allEventsJson {
        edges {
          node {
            date
            title
          }
        }
      }
    }
  `)
  const events = data.allEventsJson.edges
  return (
    <div>
      {events.map(e => (
        <div>
          <h2>{e.node.title}</h2>
          <p>{e.node.date}</p>
        </div>
      ))}
    </div>
  )
}

結果

 2020-09-25 12.10.14.png

参考

6
7
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
6
7