💬

基礎から始めるNext.js【15Data Fetch (SSG2)】

2022/11/11に公開

基礎から始めるNext.js【15Data Fetch (SSG2)】

YouTube: https://youtu.be/tmLA8MzPbK0

https://youtu.be/tmLA8MzPbK0

今回はSSGの「post」詳細ページを作成します。
こちらは「getStaticProps」と「getStaticPaths」の2つを使用します。

getStaticPaths: https://nextjs.org/docs/basic-features/data-fetching/get-static-paths

「getStaticProps」が実行されるのがビルドのタイミングになりますので、
「getServerSideProps」の時のように「query」から「id」を取得することができません。

そのため「id」を取得するために
「getStaticPaths」が使用されます。

そして、取得された「id」は
「getServerSideProps」の引数である
「context」の「params」の「id」として渡されます。

pages/ssg/[id].tsx
import Layout from '../../components/Layout'
import { Heading } from '@chakra-ui/react'
import { ListItem, UnorderedList } from '@chakra-ui/react'
import axios from 'axios'
import { GetStaticPaths, GetStaticProps } from 'next'
import { FC } from 'react'

export const getStaticPaths: GetStaticPaths = async () => {
  const res = await axios.get(`http://localhost:1337/api/posts`)
  const paths = res.data.data.map((data: Post) => {
    return { params: { id: String(data.id) } }
  })

  return {
    paths,
    fallback: false, // can also be true or 'blocking'
  }
}

export const getStaticProps: GetStaticProps = async ({ params }) => {
  try {
    const res = await axios.get(`http://localhost:1337/api/posts/${params.id}`)

    return {
      props: {
        post: res.data.data,
      },
    }
  } catch (err) {
    return {
      notFound: true,
    }
  }
}

interface Post {
  id: number
  attributes: {
    title: string
    content: string
    createdAt: string
  }
}

interface Props {
  post: Post
}

const SSGDetails: FC<Props> = ({ post }) => {
  return (
    <Layout title="Next App TopPage" content="Generated by create next app">
      <Heading as="h1" size="4xl" mb={2}>
        Post Title: {post && post.attributes.title}
      </Heading>
      <UnorderedList listStyleType="none">
        <ListItem fontSize={30} mb={1}>
          {post && post.attributes.content}
        </ListItem>
      </UnorderedList>
    </Layout>
  )
}

export default SSGDetails

Discussion