| 1 | "use client"; |
| 2 | |
| 3 | import { getViewURL, validateEmailAddress } from "@better-auth-ui/core"; |
| 4 | import { useAuth, useChangeEmail |
| 5 | import { useEffect } |
| 6 | import { toast } |
| 7 | |
| 8 | import { Card, CardContent |
| 9 | import { Field, FieldLabel |
| 10 | import { Input } |
| 11 | import { Skeleton } |
| 12 | import { cn } |
| 13 | import { isAuthFormFieldInvalid, useAuthForm |
| 14 | |
| 15 | export type ChangeEmailProps |
| 16 | className?: string |
| 17 | }; |
| 18 | |
| 19 | /** Render a card containing a form to view and update the authenticated user's email. */ |
| 20 | export function ChangeEmail({ |
| 21 | const { authClient, |
| 22 | const { data: |
| 23 | |
| 24 | const { mutateAsync: |
| 25 | onSuccess: () => |
| 26 | }); |
| 27 | |
| 28 | const form = |
| 29 | defaultValues: { email: "" |
| 30 | onSubmit: async ( |
| 31 | await changeEmail({ |
| 32 | callbackURL: getViewURL( |
| 33 | baseURL, |
| 34 | basePaths.settings, |
| 35 | viewPaths.settings.account |
| 36 | ), |
| 37 | newEmail: value.email |
| 38 | }), |
| 39 | }); |
| 40 | |
| 41 | useEffect(() => |
| 42 | if (session) form |
| 43 | }, [form, |
| 44 | |
| 45 | return ( |
| 46 | <div> |
| 47 | <h2 className="text-sm font-semibold mb-3 |
| 48 | {localization.settings.changeEmail |
| 49 | </h2> |
| 50 | |
| 51 | <form.AppForm> |
| 52 | <form.AuthFormRoot> |
| 53 | <Card className={ |
| 54 | <CardContent className=" |
| 55 | <form.AppField |
| 56 | name="email" |
| 57 | validators={{ |
| 58 | onChange: ({ value |
| 59 | validateEmailAddress(value, { |
| 60 | invalidMessage: localization.auth |
| 61 | requiredMessage: localization.auth |
| 62 | }), |
| 63 | }} |
| 64 | > |
| 65 | {(field) => |
| 66 | const isInvalid = |
| 67 | return ( |
| 68 | <Field data-invalid={ |
| 69 | <FieldLabel htmlFor=" |
| 70 | {localization.auth.email |
| 71 | </FieldLabel> |
| 72 | {session ? ( |
| 73 | <Input |
| 74 | id="email" |
| 75 | name={field.name |
| 76 | type="email" |
| 77 | autoComplete="email" |
| 78 | value={field.state |
| 79 | onBlur={field.handleBlur |
| 80 | onChange={(event) |
| 81 | field.handleChange(event |
| 82 | } |
| 83 | placeholder={localization.auth |
| 84 | disabled={isPending} |
| 85 | required |
| 86 | aria-invalid={isInvalid} |
| 87 | /> |
| 88 | ) : ( |
| 89 | <Skeleton> |
| 90 | <Input className=" |
| 91 | </Skeleton> |
| 92 | )} |
| 93 | <field.AuthFormFieldError /> |
| 94 | </Field> |
| 95 | ); |
| 96 | }} |
| 97 | </form.AppField> |
| 98 | </CardContent> |
| 99 | |
| 100 | <CardFooter> |
| 101 | <form.AuthFormSubmitButton |
| 102 | isPending={isPending} |
| 103 | size="sm" |
| 104 | disabled={isPending || |
| 105 | > |
| 106 | {localization.settings.updateEmail |
| 107 | </form.AuthFormSubmitButton> |
| 108 | </CardFooter> |
| 109 | </Card> |
| 110 | </form.AuthFormRoot> |
| 111 | </form.AppForm> |
| 112 | </div> |
| 113 | ); |
| 114 | } |