I have a formErrors
state like so:
const [formErrors, setFormErrors] = useState({});
And I have an onSubmit()
handler like so:
const onSubmit = () => {
validateForm();
if(formErrors.length === 0) {
// submit form
}
}
The validateForm()
function merely populates formErrors
if there are errors.
This onSubmit
is triggered via a "Submit" button's onClick
property.
So what happens is:
- I click "Submit".
onSubmit()
method gets called.validateForm()
is called.setFormErrors()
is called from withinvalidateForm()
.- Since setting state is async, it will move to the
if(formErrors.length === 0)
line which will returntrue
at this stage. - Form gets submitted (this is the unwanted behaviour since it shouldn't be).
setFormErrors()
is done and sets formErrors to[error1, error2]
. MeansformErrors.length
should really be> 0
.
State not updating immediately is causing a bug where in I am able to submit the form even if there are errors present due to the condition being true
first before becoming false
(where the onSubmit()
func has already finished executing).
How to resolve this issue?