🦁

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

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

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

YouTube: https://youtu.be/yfOxiSS6eTs

https://youtu.be/yfOxiSS6eTs

今回は「post」の詳細ページの作成になります。
Next.jsのダイナミックルートを使用して
各postの内容を表示します。

pages/clientside/[id].tsx
import Layout from '../../components/Layout'
import { Heading } from '@chakra-ui/react'

import { ListItem, UnorderedList } from '@chakra-ui/react'
import { useEffect, useState } from 'react'
import axios from 'axios'
import { useRouter } from 'next/router'

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

export default function ClientSideDetails() {
  const [post, setPost] = useState<Post | null>(null)
  const router = useRouter()
  const { id } = router.query

  useEffect(() => {
    const getPostById = async () => {
      try {
        const res = await axios.get(`http://localhost:1337/api/posts/${id}`)
        console.log(res.data.data)
        setPost(res.data.data)
      } catch (err) {}
    }

    getPostById()
  }, [id])

  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>
  )
}
pages/clientside/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 { useEffect, useState } from 'react'
import axios from 'axios'

export default function ClientSide() {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    ;(async () => {
      const res = await axios.get(`http://localhost:1337/api/posts`)
      console.log(res.data.data)
      setPosts(res.data.data)
    })()
  }, [])

  return (
    <Layout title="Next App TopPage" content="Generated by create next app">
      <Heading as="h1" size="4xl" mb={2}>
        Client Side Posts List
      </Heading>
      <UnorderedList>
        {posts &&
          posts.map((post) => (
            <ListItem key={post.id} fontSize={20} mb={1}>
              <Link href={`/clientside/${post.id}`}>
                {post.attributes.title}
              </Link>
            </ListItem>
          ))}
      </UnorderedList>
    </Layout>
  )
}

Discussion

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