Files
property-management-network/components/shared/delete-button.tsx
T

63 lines
1.6 KiB
TypeScript
Raw Normal View History

"use client"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { Trash2 } from "lucide-react"
import { ConfirmModal } from "@/components/ui/confirm-modal"
import { toast } from "sonner"
interface DeleteButtonProps {
id: string
endpoint: string
label?: string
onDeleted?: () => void
}
export function DeleteButton({ id, endpoint, label = "this item", onDeleted }: DeleteButtonProps) {
const router = useRouter()
const [open, setOpen] = useState(false)
const [loading, setLoading] = useState(false)
async function handleDelete() {
setLoading(true)
try {
const res = await fetch(`${endpoint}/${id}`, { method: "DELETE" })
if (!res.ok) {
const data = await res.json().catch(() => null)
toast.error(data?.error ?? "Failed to delete")
return
}
toast.success("Deleted successfully")
if (onDeleted) onDeleted()
else router.refresh()
} catch {
toast.error("Network error — please try again")
} finally {
setLoading(false)
setOpen(false)
}
}
return (
<>
<button
onClick={() => setOpen(true)}
className="text-white/20 hover:text-red-400 transition"
title="Delete"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
<ConfirmModal
open={open}
title="Delete item?"
description={`Are you sure you want to delete ${label}? This cannot be undone.`}
confirmLabel="Delete"
loading={loading}
onConfirm={handleDelete}
onCancel={() => setOpen(false)}
/>
</>
)
}