🐙

【Next.js】基礎から始めるNext.js API Routes【18Update Form】

2022/12/27に公開

【18Update Form】

YouTube: https://youtu.be/JgCM_3QDyBM

https://youtu.be/JgCM_3QDyBM

今回はユーザー情報のアップデートフォームの作成を行います。

components/UpdateForm.tsx
import { Button, Label, TextInput } from 'flowbite-react'
import { ChangeEvent, FC, SyntheticEvent, useState } from 'react'

interface UserData {
  id: number
  email: string
  name: string
}

interface Props {
  user: UserData
}

const UpdateForm: FC<Props> = ({ user }) => {
  const [formData, setFormData] = useState({
    email: user.email,
    name: user.name,
  })

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { value, name } = e.target
    setFormData({ ...formData, [name]: value })
  }

  const handleSubmit = async (e: SyntheticEvent) => {
    e.preventDefault()
    const res = await fetch(`/api/users/${user.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })

    if (res.status === 200) {
      const user = await res.json()
      console.log(user)
    } else {
      console.log(`${res.status} something went wrong`)
    }
  }

  return (
    <div className="w-60">
      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <div>
          <div className="mb-2 block">
            <Label htmlFor="email1" value="Your email" />
          </div>
          <TextInput
            id="email1"
            type="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            required={true}
          />
        </div>
        <div>
          <div className="mb-2 block">
            <Label htmlFor="username" value="Your name" />
          </div>
          <TextInput
            id="username"
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
            required={true}
          />
        </div>
        <Button type="submit">Update User</Button>
      </form>
    </div>
  )
}

export default UpdateForm
pages/users/[id].tsx
import { useEffect, useState } from 'react'
import Layout from '../../components/Layout'
import { User } from '@prisma/client'
import UserCard from '../../components/UserCard'
import { useRouter } from 'next/router'
import UpdateForm from '../../components/UpdateForm'

export default function UserDetails() {
  const [user, setUser] = useState<Pick<User, 'id' | 'email' | 'name'>>()

  const router = useRouter()
  const { id } = router.query

  useEffect(() => {
    ;(async () => {
      if (router.isReady) {
        const res = await fetch(`/api/users/${id}`)
        const user = await res.json()
        setUser(user)
        console.log(user)
      }
    })()
  }, [id])

  return (
    <Layout>
      <div className="flex flex-col justify-center items-center">
        <h2 className="text-4xl font-black font-sans p-4 mt-6">Update Form</h2>
        {user && <UpdateForm user={user} />}

        <h2 className="text-4xl font-black font-sans p-4 mt-6">User Details</h2>
        <div className="flex flex-wrap w-full justify-center items-center gap-3">
          {user && <UserCard user={user} isDetailds={true} />}
        </div>
      </div>
    </Layout>
  )
}

Discussion