Display auth.js session on first render
Unanswered
English Lop posted this in #help-forum
English LopOP
I have a settings page (client component) that allows the currently logged in user to view their account information and update that information via a react-hook-form. I use auth.js (specifically,
useSession
hook from "next-auth/react") to get the currently logged in user. Upon testing this, when logging in via Google OAuth, the account information displays correctly on first render in the form. However, when I log in with credentials provider, the account information does not display at all until a full page refresh. "use client";
…
const SettingsPage = () => {
const user = useCurrentUser();
const { update } = useSession();
const [isPending, startTransition] = useTransition();
const {
register,
handleSubmit,
reset,
watch,
setValue,
formState: { errors },
} = useForm<z.infer<typeof SettingsSchema>>({
resolver: zodResolver(SettingsSchema),
defaultValues: {
name: user?.name || undefined,
...
},
});
useEffect(() => {
if (user) {
reset({
password: undefined,
newPassword: undefined,
name: user.name || undefined,
email: user.email || undefined,
role: user.role || undefined,
isTwoFactorEnabled: user.isTwoFactorEnabled || undefined,
});
}
}, [user, reset]);
const onSubmit = (values: z.infer<typeof SettingsSchema>) => {
const transformedValues = {
...values,
password: values.password || undefined,
newPassword: values.newPassword || undefined,
};
startTransition(() => {
settings(transformedValues)
.then((data) => {
if (data.error) {
toast.error(data.error);
} else {
update();
toast.success(data.success || "Settings updated successfully.");
}
})
.catch(() => toast.error("An unexpected error occurred."));
});
};
...
2 Replies
English LopOP
My returned component:
return (
<DefaultLayout>
…
<form onSubmit={handleSubmit(onSubmit)}>
{/* Personal Information Section */}
<div className="border-b px-7 py-4 dark:border-dark-3">
<h3 className="font-bold text-dark dark:text-white">
Personal Information
</h3>
</div>
<div className="p-7">
<div className="mb-5.5 flex flex-col gap-5.5 sm:flex-row">
{/* Full Name */}
<div className="w-full sm:w-1/2">
<label
htmlFor="name"
>
Name
</label>
<input
{...register("name")}
type="text"
id="name"
placeholder="Your Name"
/>
{errors.name && (
<p className="mt-1 text-sm text-red-500">
{errors.name.message}
</p>
)}
</div>
….
{/* Buttons */}
<div className="mt-10 flex justify-end gap-3 px-7 pb-7">
<button
type="button"
onClick={() => reset()}
className="flex justify-center rounded-[7px] border border-stroke px-6 py-[7px] font-medium text-dark hover:shadow-1 dark:border-dark-3 dark:text-white"
>
Cancel
</button>
<button
type="submit"
disabled={isPending}
className="flex justify-center rounded-[7px] bg-primary dark:bg-[#713AC9] px-6 py-[7px] font-medium text-gray-2 hover:bg-opacity-90"
>
{isPending ? "Saving..." : "Save"}
</button>
</div>
</form>
…
</DefaultLayout>
);
};
export default SettingsPage;