Next.js Discord

Discord Forum

useActionState's isPending is false when used together with react-hook-form

Unanswered
Sweat bee posted this in #help-forum
Open in Discord
Avatar
Sweat beeOP
Hi! I am having some trouble getting my form to work as I want. I am using react-hook-form together with useActionState. The problem is that isPending is always false. As far as I can read it is because
`onSubmit={form.handleSubmit(() => formRef.current?.submit())}
` overrides the default React submit.

My goal is to use react-hook-form to handle client side validation and use the useActionState's isPending to disable the button when the server action is processing. I have tried multiple different ways to submitting the form but I can't find something that solves everything.

Does any of you have an idea?

My form looks like this:

export default function LoginForm() {
  const [state, formAction, isPending] = useActionState<
    LoginFormState,
    FormData
  >(login, {
    message: '',
  });

  const form = useForm<loginFormSchema>({
    resolver: zodResolver(loginFormSchema),
    defaultValues: {
      ...(state?.fields ?? {}),
    },
  });

  const formRef = useRef<HTMLFormElement>(null);

  return (
    <div>
      <h1 className="text-3xl">Sign In</h1>
      <form
        onSubmit={form.handleSubmit(() => formRef.current?.submit())}
        action={formAction}
        ref={formRef}
        id="loginForm"
      >
        <input
          id="email"
          placeholder="E-mail"
          type="email"
          {...form.register('email')}
        />
        <input
          id="password"
          type="password"
          placeholder="Password"
          {...form.register('password')}
        />
        <button
          form="loginForm"
          type="submit"
          disabled={isPending}
        >
          {isPending ? <LoadingSpinner color="white" /> : 'Login'}
        </button>
      </form>

      <Link href="#" className="my-2">
        Forgot password?
      </Link>
    </div>
  );
}

0 Replies