Next.js Discord

Discord Forum

Form onSubmit with server actions?

Answered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
In order to use react-hook-form with server actions, can I call a server action in a submit hander function that is passed to the form onSubmit attribute or does the form action attribute have to be used rather than the form onSubmit attribute?

9 Replies

Polar bearOP
Hi @Ray ,
Thanks for the reply! I have read through this and it seems like there are a lot of different thoughts being thrown around there however, isn't it just as simple as calling the server action function from directly in the handleSubmit function that is being passed to the form onSubmit without any additional logic needed?
Answer
i'm using this approach because it handle the form state itself
if using the action props, the form will lose the value when error occur on the server action
also, you need to set the error with form.setError if the action fail
Polar bearOP
Got it! So the only thing new here is using useTransition startTransition to call the action in the submit handler and using isPending rather than using form.formState.isSubmitting to handle the loading state? Along with also manually setting the error with form.setError?
yes
Polar bearOP
Great, thanks again!