پرتوپرتو

دیالوگ تأیید حذف

الگوی دیالوگ تأیید برای عملیات مخرب مثل حذف

معرفی

این الگو نشان می‌دهد چگونه یک دیالوگ تأیید برای عملیات حذف بسازید که:

  • از AlertDialog برای عملیات مخرب استفاده می‌کند
  • وضعیت بارگذاری دکمه را مدیریت می‌کند
  • پس از تأیید، عملیات async را اجرا می‌کند

نمونه بصری

کد کامل

'use client'

import { useState } from 'react'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
  Button,
} from '@parto-system-design/ui'

interface DeleteConfirmProps {
  itemName: string
  onDelete: () => Promise<void>
}

export function DeleteConfirmDialog({ itemName, onDelete }: DeleteConfirmProps) {
  const [isDeleting, setIsDeleting] = useState(false)

  async function handleDelete() {
    setIsDeleting(true)
    try {
      await onDelete()
    } finally {
      setIsDeleting(false)
    }
  }

  return (
    <AlertDialog>
      <AlertDialogTrigger asChild>
        <Button variant="destructive">حذف</Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>آیا از حذف مطمئن هستید؟</AlertDialogTitle>
          <AlertDialogDescription>
            این عملیات غیرقابل بازگشت است. «{itemName}» به‌طور کامل حذف خواهد شد و امکان بازیابی آن وجود ندارد.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>انصراف</AlertDialogCancel>
          <AlertDialogAction asChild>
            <Button variant="destructive" isLoading={isDeleting} onClick={handleDelete}>
              حذف
            </Button>
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

نکات

  • همیشه از AlertDialog به‌جای Dialog برای تأیید عملیات مخرب استفاده کنید
  • دکمه لغو را در حین اجرا disabled کنید تا از تداخل جلوگیری شود
  • متن توضیحی باید پیامدهای عمل را به‌وضوح بیان کند