useActionState, server actions and no FormData
Answered
Transvaal lion posted this in #help-forum
Transvaal lionOP
Hi everyone, I have a really complex multistep form built with shadcn, zod and react hook form. On the server, I have a server action that receives the formData; on the client, I have a useActionState with the server action. I insert the action inside <form action={action}> like always. But with this multiform steps, in the server action I receive no formData (it's empty) while on frontend the react hook form has everything. Is this something DOM related? How can I send react hook form data to server action?
Answered by Cinnamon Teal
I don't think the
Instead, you will have to call the action function manually inside the
Something like this:
I would be glad if somehow my understanding is wrong and there is a workaround for this as I had to look into other form libraries recently because of this.
useActionState setup would work with RHF. Assuming you are passing the RHF's handleSubmit to the onSubmit of your form, RHF will prevent the default behavior of the form making it not submit the data into the action.Instead, you will have to call the action function manually inside the
handleSubmit of RHF.Something like this:
<form
onSubmit={form.handleSubmit(async (data) => {
const response = await yourAction(data)
})
>I would be glad if somehow my understanding is wrong and there is a workaround for this as I had to look into other form libraries recently because of this.
2 Replies
Cinnamon Teal
I don't think the
Instead, you will have to call the action function manually inside the
Something like this:
I would be glad if somehow my understanding is wrong and there is a workaround for this as I had to look into other form libraries recently because of this.
useActionState setup would work with RHF. Assuming you are passing the RHF's handleSubmit to the onSubmit of your form, RHF will prevent the default behavior of the form making it not submit the data into the action.Instead, you will have to call the action function manually inside the
handleSubmit of RHF.Something like this:
<form
onSubmit={form.handleSubmit(async (data) => {
const response = await yourAction(data)
})
>I would be glad if somehow my understanding is wrong and there is a workaround for this as I had to look into other form libraries recently because of this.
Answer
Transvaal lionOP
Hi, hank you for the response. I switched from form action={action} to "onSubmit" and edited the server action, now it's working. Thanks!