Server actions and react-hook-form
Unanswered
Perro de Presa Mallorquin posted this in #help-forum
Perro de Presa MallorquinOP
When reading the [server actions docs](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), it seems like the recommended error handling method to return an error message from the server action. Then it says to use
Instead, I've been calling the server action through react-hook-form using the
useFormState and pass the server action into the action prop of the form element. I'm using react-hook-form and zod, but unfortunately validations don't seem to be performed if I pass in the server action through action.Instead, I've been calling the server action through react-hook-form using the
onSubmit prop like so: <form onSubmit={form.handleSubmit(serverAction)} />, which unfortunately means I have no way of accessing the server action return message since I'm not using useFormState. Have other people found a way around this? Are there any other ways of returning errors from the server action or structuring this form?3 Replies
@Perro de Presa Mallorquin When reading the [server actions docs](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations), it seems like the recommended error handling method to return an error message from the server action. Then it says to use `useFormState` and pass the server action into the `action` prop of the `form` element. I'm using react-hook-form and zod, but unfortunately validations don't seem to be performed if I pass in the server action through `action`.
Instead, I've been calling the server action through react-hook-form using the `onSubmit` prop like so: `<form onSubmit={form.handleSubmit(serverAction)} />`, which unfortunately means I have no way of accessing the server action return message since I'm not using `useFormState`. Have other people found a way around this? Are there any other ways of returning errors from the server action or structuring this form?
which unfortunately means I have no way of accessing the server action return message since I'm not using useFormStateYou have
Just create another function for handleSubmit and call the server action in that function
{form.handleSubmit(onSubmit)} />
function onSubmit(data){
const res = await serverAction(data)
if(res.error) form.setError("root.serverError",{
....
})
}