Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

2.9 KB
Raw Blame
"use client";

import DeleteAccountSection from "@/ui/account/delete-account";
import UpdateDefaultWorkspace from "@/ui/account/update-default-workspace";
import UpdateSubscription from "@/ui/account/update-subscription";
import UploadAvatar from "@/ui/account/upload-avatar";
import UserId from "@/ui/account/user-id";
import { PageWidthWrapper } from "@/ui/layout/page-width-wrapper";
import { Form } from "@dub/ui";
import { useSession } from "next-auth/react";
import { toast } from "sonner";

export function SettingsPageClient() {
  const { data: session, update, status } = useSession();

  const patchUser = async (body: Record<string, unknown>) => {
    const res = await fetch("/api/user", {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (res.status !== 200) {
      const { error } = await res.json();
      throw new Error(error.message);
    }

    const isPendingEmailChange =
      typeof body.email === "string" && body.email !== session?.user?.email;

    // Email isn't updated until the user confirms via link — skip session refresh
    if (!isPendingEmailChange) {
      await update();
    }
  };

  const requestSubmit = ({
    body,
    onSuccess,
  }: {
    body: Record<string, unknown>;
    onSuccess: () => void;
  }): Promise<void> =>
    patchUser(body)
      .then(onSuccess)
      .catch((error) => {
        toast.error(error.message);
      })
      .then(() => undefined);

  return (
    <PageWidthWrapper className="mb-8 grid gap-8">
      <Form
        title="Your Name"
        description="This is your display name on Dub."
        inputAttrs={{
          name: "name",
          defaultValue:
            status === "loading" ? undefined : session?.user?.name || "",
          placeholder: "Steve Jobs",
          maxLength: 32,
        }}
        helpText="Max 32 characters."
        handleSubmit={(data) =>
          requestSubmit({
            body: data,
            onSuccess: () => {
              toast.success("Successfully updated your name!");
            },
          })
        }
      />
      <Form
        title="Your Email"
        description="This will be the email you use to log in to Dub and receive notifications. A confirmation is required for changes."
        inputAttrs={{
          name: "email",
          type: "email",
          defaultValue: session?.user?.email || undefined,
          placeholder: "[email protected]",
        }}
        helpText={<UpdateSubscription />}
        handleSubmit={(data) =>
          requestSubmit({
            body: data,
            onSuccess: () => {
              toast.success(
                `A confirmation email has been sent to ${data.email}.`,
              );
            },
          })
        }
      />
      <UploadAvatar />
      <UserId />
      <UpdateDefaultWorkspace />
      <DeleteAccountSection />
    </PageWidthWrapper>
  );
}