winofy-front/src/components/customer/clear-cart-button.tsx
2026-08-31 16:03:11 +03:30

48 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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>
);
}