I have the following method in a form component:
validateForm () {
this.setState({isValid: true});
this.formFields.forEach(field => {
let isValid = field.ref.current.validateField();
console.log('Field isValid?', isValid);
if (!isValid) {
this.setState({isValid: false});
}
console.log('Form isValid?', this.state.isValid);
});
return this.state.isValid;
}
When it is called it sets the form state isValid
as true
. And then loops through the child components we store in the formFields
and finds out if any of them are invalid at which point it will mark the form is invalid if any return an invalid response.
Using the console logs I've found that the state for the form is always the previous state console.log('Form isValid?', this.state.isValid);
until I call the method again and then it returns the correct state value...
I've seen something similar happen in ActiveRecord in Rails whereby you need to called reload
on the model to make sure you're getting the latest state due to caching... Does React have something similar?