How to know the form is submitted with Server Actions
Unanswered
Ant posted this in #help-forum
AntOP
Hello,
I'm looking for the best way to know the form is succesfully submitted and a succesful response returned.
I know about
But, here's the problem.
Form submitted, success is true. If you submit the form again success is still true so the state isnt updated. I want to close the dialog when the success is true even after resubmissions. How I can handle this ?
I'm looking for the best way to know the form is succesfully submitted and a succesful response returned.
I know about
useFormState
which works by passing an inital state and then updating the state in the server action. But, here's the problem.
const [formState, formAction] = useFormState(editProvider, {success:null});
formState?.success // true after first response
Form submitted, success is true. If you submit the form again success is still true so the state isnt updated. I want to close the dialog when the success is true even after resubmissions. How I can handle this ?
14 Replies
https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations#error-handling
This is basically the general idea, for your case you can have a success variable, and you set it to true at the top of the action and then set it to false at the end of the action
This is basically the general idea, for your case you can have a success variable, and you set it to true at the top of the action and then set it to false at the end of the action
AntOP
Thank you but I didnt understand how that would work in my case
AntOP
I forgot that I have access to state inside the action as well, thank you.
No worries, just mark the question as resolved
.
AntOP
Sorry to bump you again about this, but I couldnt figure this out, I need to reset the state in the client so resetting it at the top of the action doesnt change anything
well the state is shared so both the client (where the form exists) and the server action both have the same variable
so you can just use a useEffect to reset the value
So basically, when you submit the form, make it a onSubmit(){
//set the form submitted to true
serverAction()
//set it to false
}
//set the form submitted to true
serverAction()
//set it to false
}
you can call serverActions as normal functions and still have them run on the server
AntOP
But that disables progressive enhancement as far as I know ?
that is true
AntOP
That kills the benefit of a server action for me, thank you anyway. I'll try to come up with something else.
Alrighty!