import { useRouter } from "next/router"; import { t } from "@lingui/core/macro"; import { useEffect, useState } from "react"; import Button from "~/components/Button"; import { PageHead } from "~/components/PageHead"; import PatternedBackground from "~/components/PatternedBackground"; type UnsubscribeStatus = "idle" | "processing" | "success" | "error"; export default function UnsubscribePage() { const router = useRouter(); const [token, setToken] = useState(""); const [status, setStatus] = useState("idle"); const [errorMessage, setErrorMessage] = useState(null); useEffect(() => { if (!router.isReady) return; const value = router.query.token; if (typeof value === "string") { setToken(value); } else if (Array.isArray(value)) { setToken(value[0] ?? ""); } else { setToken(""); } }, [router.isReady, router.query.token]); const handleUnsubscribe = async () => { if (!token) { setStatus("error"); setErrorMessage( t`Your unsubscribe link is missing a token. Please open the latest email and try again.`, ); return; } setStatus("processing"); setErrorMessage(null); try { const response = await fetch("/api/unsubscribe", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token }), }); if (!response.ok) { const payload = (await response.json().catch(() => null)) as { error?: string; } | null; throw new Error( payload?.error ?? "We couldn't update your preferences. Please try again.", ); } setStatus("success"); } catch (error) { setStatus("error"); setErrorMessage( t`We couldn't update your preferences. Please try again.`, ); } }; const title = t`Unsubscribe`; return ( <>

{t`Do you want to unsubscribe?`}

{t`Confirm your email preferences:`}

{status === "success" && (

{t`You have been unsubscribed!`}

)} {status === "error" && (

{errorMessage}

)}
); }