"use client"; import {useEffect} from "react"; import {Button} from "@/components/ui/button"; import {Input} from "@/components/ui/input"; import {AlertCircle, Loader2} from "lucide-react"; import {useMutation} from "@tanstack/react-query"; import {toast} from "sonner"; import {useRouter} from "next/navigation"; import {authClient} from "@/lib/auth/auth-client"; import {User} from "@/db/schema/02_user"; import {Form, FormControl, FormField, FormItem, FormLabel, FormMessage, useZodForm} from "@/components/ui/form"; import {EmailSchema, EmailSchemaType} from "./schemas/account.schema"; import {BetterAuthError} from "@/types/auth"; interface ProfileAccountProps { user: User; } export function ProfileAccount({user}: ProfileAccountProps) { const router = useRouter(); useEffect(() => { let interval: NodeJS.Timeout; interval = setInterval(async () => { router.refresh(); }, 5000); return () => { if (interval) clearInterval(interval); }; }); const emailForm = useZodForm({ schema: EmailSchema, defaultValues: { email: user.email, }, }); const {mutate: updateEmail, isPending: isUpdatingEmail} = useMutation({ mutationFn: async (values: EmailSchemaType) => { const {error} = await authClient.changeEmail({ newEmail: values.email, callbackURL: window.location.href, }); if (error) throw error; return values.email; }, onSuccess: (newEmail) => { toast.success("Email updated successfully."); emailForm.reset({email: newEmail}); router.refresh(); }, onError: (error: BetterAuthError) => { if (error.code === "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL") { toast.error("User already exists, use another email address!"); emailForm.reset({email: user.email}); router.refresh() } else { toast.error("An error occurred while trying to update your password!"); } }, }); const {mutate: resendVerificationEmail, isPending: isResendingVerification} = useMutation({ mutationFn: async () => { const currentEmailInput = emailForm.getValues("email"); let error: BetterAuthError | null = null; if (currentEmailInput === user.email) { const sendVerification = await authClient.sendVerificationEmail({ email: currentEmailInput, callbackURL: window.location.href, }); error = sendVerification.error; } else { const result = await authClient.changeEmail({ callbackURL: window.location.href, newEmail: currentEmailInput, }); error = result.error; } if (error) throw error; }, onSuccess: () => { toast.success("Verification email resent successfully."); }, onError: (e: BetterAuthError) => { console.error(e); toast.error("Failed to resend verification email."); }, }); return (
Update your email and preferences.