Form onSubmit with server actions?
Answered
Polar bear posted this in #help-forum
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?
Answered by Ray
sorry wrong link. please read this instead
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1554578614
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1554578614
9 Replies
yes you can
check this out
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1789632091
check this out
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1789632091
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?
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?
sorry wrong link. please read this instead
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1554578614
https://github.com/react-hook-form/react-hook-form/issues/10391#issuecomment-1554578614
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 failPolar 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!