How to resolve a react-hook-form from the client and server in Next.js

41 Views Asked by At

I am using a react-hook-form use zod as a resolver. It has a action attribute to points to a function (RegisterAccount) that runs on the server and parses the form values and returns a Promise<ZodError>.

const form = useForm<z.infer<typeof registerFormSchema>>({
    resolver: zodResolver(registerFormSchema),
    defaultValues: {
        // ...
    }
})
<form action={RegisterAccount}>
    // ...
</form>

Normally I'm pretty sure I'm supposed to do something like onSubmit={form.handleSubmit(onSubmit)} but when I add that, RegisterAccount does not get called at all.

I'm also trying to use the ZodError that is returned from the server and somehow injecting that ZodError into the form. But I have no idea how to start on that.

1

There are 1 best solutions below

0
Ahmed Abdelbaset On BEST ANSWER

Try to write a client action that validates the data then calls the server action


async function function action(formData: FormData) {
  const isValid = await form.trigger()

  if (!isValid) return 

  await RegisterAccount(formData)

  form.reset()
}


return <form action={action}>
    // ...
</form>

Note: some of react-hook-form (like isSubmiting, isSubmited, etc...) won't work with this approach

See this issue: https://github.com/react-hook-form/react-hook-form/issues/10391

Or you can remove the action prop and call the server action directly within onSubmit callback