😊

【Next.js】基礎から始めるNext.js API Routes【19Delete User】

2022/12/28に公開約4,000字

【19Delete User】

YouTube: https://youtu.be/Dn4c0CGEIzs

https://youtu.be/Dn4c0CGEIzs

今回はユーザーの削除の処理を実装します。

まずは前回の動画で一部Typescriptのエラー表記が出ていましたので
今回の動画で先にこちらの対応を行っています。

ボタンの色を変える方法はこちらを参考にしてください。

https://flowbite-react.com/buttons

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 | null
}

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'
import { Button } from 'flowbite-react'

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])

  const handleDelete = async () => {
    if (window.confirm('Delete really?')) {
      const res = await fetch(`/api/users/${user?.id}`, {
        method: 'DELETE',
      })

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

  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 flex-col w-full justify-center items-center gap-3">
          {user && <UserCard user={user} isDetailds={true} />}
          {user && (
            <Button color="failure" onClick={handleDelete}>
              User Delete
            </Button>
          )}
        </div>
      </div>
    </Layout>
  )
}

Discussion

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