Gatsbyノート5 (Contentful-1)


参考

学習内容

  • Contentfulを使ってブログ一覧の情報を更新する

Contentful

手順

  • Try for free を押す
  • Sign up

  • 左の I create content を選択
  • Get started を押す

The example projectが作成される(ここでは使わない)

手順(新規プロジェクトの作成)

  • 左上のメニューから、「+Create space」を押す

  • communityを選択

データ構造を作成する

1.Content modal => Add content type

  • Api Identifierとは、Apiでデータを取得する時の識別子

2.Add field

データ作成

Field IDはGraphQLでデータ取得する際に利用する

  • Title
    • Text
  • Slug
    • Text
  • created date
    • Date and time
  • Thumbnail
    • Media
    • One fileを選択
  • body
    • Rich text

  • Saveを押す

  • ヘッダーメニューからContentを選択 => Add Blog Postを押す

  • 管理画面が出来ているので、投稿を入力する

  • 3件のブログ記事の入力を行った

GraphQLでcontentfulのデータを取得する

  • gatsby-source-contentful

yarn add gatsby-source-contentful
  • gatsby-config.jsにプラグインの設定を追記
  • Contentful
    • Settings => API keys
      • spaceId
      • accessToken
    • .envファイルにapaceIdとaccessTokenを記述し、gatsby-config.jsで使う
gatsby-config.js

const dotenv = require("dotenv")

if (process.env.ENVIRONMENT !== "production") {
  dotenv.config()
}

:
:
//(省略)

    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: process.env.CONTENTFUL_SPACE_ID,
        accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
      },
    },
  • GraphQL Playgroundでデータ取得を試す

src/pages/index.js

import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Layout from "../components/layout"
import Kv from "../components/kv"
import BlogItem from "../components/blogItem"
import {Container, Row, Col} from 'react-bootstrap'

const IndexPage = () => {
  // contentfulからデータを取得
  const data = useStaticQuery(graphql`
    query {
      allContentfulBlogPost(sort: {
        fields: createdDate,
        order: ASC
      }) {
        edges {
          node {
            title
            slug
            createdDate(formatString: "YYYY/MM/DD")
            thumbnail {
              fluid {
                src
              }
            }
          }
        } 
      }
    }  
  `)
  return (
    <Layout>
      <Kv />
      <Container>
        <Row>
          {
            data.allContentfulBlogPost.edges.map((edge, index) => (
              <Col sm={4} key={index}>
                <BlogItem
                  title={edge.node.title}
                  date={edge.node.createDate}
                  src={edge.node.thumbnail.fluid.src}
                  link={`blog/${edge.node.slug}`} />
              </Col>
            ))
          }
        </Row>
      </Container>
    </Layout>
  )
}

export default IndexPage