Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

1.2 KB
Raw Blame
import { useOptimisticUpdate } from "@/components/hooks/use-optimistic-update";
import { Switch } from "@/components/ui/switch";

export const UpdateMailSubscribe = () => {
  const { data, isLoading, update } = useOptimisticUpdate<{
    subscribed: boolean;
  }>("/api/user/subscribe", {
    loading: "Updating email preferences...",
    success: "Your email preferences have been updated!",
    error: "Failed to update email preferences. Please try again.",
  });

  const subscribe = async (checked: boolean) => {
    const method = checked ? "POST" : "DELETE";
    const res = await fetch("/api/user/subscribe", {
      method,
    });
    if (!res.ok) {
      throw new Error("Failed to update email preferences");
    }
    return { subscribed: checked };
  };

  return (
    <div className="flex items-center gap-x-2">
      <Switch
        checked={data?.subscribed ?? true}
        disabled={isLoading}
        onCheckedChange={(checked: boolean) => {
          update(() => subscribe(checked), { subscribed: checked });
        }}
      />
      <p className="text-sm text-muted-foreground transition-colors">
        Subscribed to product updates
      </p>
    </div>
  );
};

export default UpdateMailSubscribe;