🍣

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

2022/11/09に公開約2,400字

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

YouTube: https://youtu.be/dLWKAuT27Yc

https://youtu.be/dLWKAuT27Yc

今回は「getServerSideProps」を使用した、
「post」の詳細ページの作成について解説します。

pages/serverside/index.tsx
import Link from 'next/link'
import Layout from '../../components/Layout'
import { Heading } from '@chakra-ui/react'
import { ListItem, UnorderedList } from '@chakra-ui/react'
import axios from 'axios'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async () => {
  const res = await axios.get(`http://localhost:1337/api/posts`)

  return {
    props: {
      posts: res.data.data,
    },
  }
}

export default function ServerSide({ posts }) {
  return (
    <Layout title="Next App TopPage" content="Generated by create next app">
      <Heading as="h1" size="4xl" mb={2}>
        Server Side Posts List
      </Heading>
      <UnorderedList>
        {posts &&
          posts.map((post) => (
            <ListItem key={post.id} fontSize={20} mb={1}>
              <Link href={`/serverside/${post.id}`}>
                {post.attributes.title}
              </Link>
            </ListItem>
          ))}
      </UnorderedList>
    </Layout>
  )
}
pages/serverside/[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 { GetServerSideProps } from 'next'
import { FC } from 'react'

export const getServerSideProps: GetServerSideProps = async ({ query }) => {
  try {
    const res = await axios.get(`http://localhost:1337/api/posts/${query.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 ServerSideDetails: 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 ServerSideDetails

Discussion

ログインするとコメントできます