So I’ve got a form which sends formData to api, goes like this:
const [state, setState] = useState(true)
const handleSubmit = async e => {
const destination = state ? true : false
// Sends FormData to api
}
return (
<form onSumbit={handleSubmit}>
<div>
<button onClick={() => setState(prev => !prev)}>click</button
<button onClick={() => setState(prev => !prev)}>click</button
</div>
// some more inputs here
<input type="submit" value="Upload" />
</form>
Every time state changes it tries to submit again. It does that only for the state used in submitHandler to calculate destination. I also tried moving destination outside of submitHandler but the result is the same.
2
Answers
You need to add
type="button"
on your prev/next buttons:https://playcode.io/1495308
html forms assume that buttons are submit buttons by default:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/submit#additional_attributes
The problem you’re encountering, where the form tries to submit again every time the state changes, is likely due to the re-rendering behavior of React. Since the state update triggers re-render, the form
onSubmit
event is being registered again and causing another submission attempt.To prevent this behavior, you can make a small adjustment to your code by add type="button" to you button element.
How to prevent buttons from submitting forms