"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Notification } from "./ui"; export function OrderCancelButton({ reference }: Readonly<{ reference: string }>) { const router = useRouter(); const [pending, setPending] = useState(false); const [message, setMessage] = useState(null); async function cancel() { setPending(true); setMessage(null); try { const response = await fetch(`/api/orders/${encodeURIComponent(reference)}/cancel`, { body: JSON.stringify({ idempotencyKey: crypto.randomUUID(), reason: "Customer cancelled before payment.", }), headers: { "content-type": "application/json" }, method: "POST", }); const payload: unknown = await response.json(); if (!response.ok) { setMessage(readApiMessage(payload)); return; } router.refresh(); } catch { setMessage("The cancellation request could not be completed."); } finally { setPending(false); } } return (
{message === null ? null : (

{message}

)}
); } function readApiMessage(value: unknown): string { if ( typeof value === "object" && value !== null && "error" in value && typeof value.error === "object" && value.error !== null && "message" in value.error && typeof value.error.message === "string" ) { return value.error.message; } return "The cancellation request could not be completed."; }