48 lines
1.5 KiB
TypeScript
48 lines
1.5 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useState, useTransition } from "react";
|
||
import { useRouter, usePathname } from "next/navigation";
|
||
import { Trash2 } from "lucide-react";
|
||
import { clearCart } from "@/lib/api/cart";
|
||
|
||
export function ClearCartButton() {
|
||
const router = useRouter();
|
||
const pathname = usePathname();
|
||
const [isPending, startTransition] = useTransition();
|
||
const [error, setError] = useState<string | null>(null);
|
||
|
||
useEffect(() => {
|
||
if (!error) return;
|
||
const timeout = setTimeout(() => setError(null), 3000);
|
||
return () => clearTimeout(timeout);
|
||
}, [error]);
|
||
|
||
function handleClear() {
|
||
if (!window.confirm("سبد خرید شما بهطور کامل خالی میشود. ادامه میدهید؟")) return;
|
||
startTransition(async () => {
|
||
const result = await clearCart();
|
||
if (result.ok) {
|
||
router.refresh();
|
||
} else if (result.status === 401) {
|
||
router.push(`/login?next=${encodeURIComponent(pathname)}`);
|
||
} else {
|
||
setError(result.message);
|
||
}
|
||
});
|
||
}
|
||
|
||
return (
|
||
<div className="flex flex-col items-end gap-1">
|
||
<button
|
||
type="button"
|
||
onClick={handleClear}
|
||
disabled={isPending}
|
||
className="flex items-center gap-1.5 text-xs font-medium text-error disabled:opacity-40"
|
||
>
|
||
<Trash2 className="h-3.5 w-3.5" />
|
||
خالی کردن سبد
|
||
</button>
|
||
{error && <p className="text-xs text-error">{error}</p>}
|
||
</div>
|
||
);
|
||
}
|