Next.js Discord

Discord Forum

Populate auth.js session on page load in react-hook-form

Unanswered
English Lop posted this in #help-forum
Open in Discord
Avatar
English LopOP
Hi, I have a settings page with a react-hook-form in it. I am getting the auth.js user session from a custom hook,
useCurrentUser
. I would like the react-hook-form default values to be populated with the user session values, for example,
user.name
for the
name
input field on first page load. However, that does not happen on first page load, only on refresh. Here's my code:
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,
      email: user?.email || undefined,
      role: user?.role || undefined,
      isTwoFactorEnabled: user?.isTwoFactorEnabled || undefined,
      password: undefined,
      newPassword: 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."));
    });
  };

0 Replies