I have a simple form with a couple text inputs. One is required, one is not. I have a custom input that adds to a list every time the user hits enter and is required. When the user submits the form, I check that all required fields have a value.
If I have entered a value for all required fields and hit enter, I will get a message that the form is invalid. If I hit enter one or two more times, I will get a finally get a message that my form is valid.
When I console.log the values of prioritiesArrayValid, demoFieldTwoValid, and formValid on form submit, they will all be their default value of false until I hit enter a few times
I know my question is a common one. I know it has something to do with setState and async but I can't see the issue.
Below is the code that run when the user hits enter.
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let prioritiesArrayValid = this.state.prioritiesArrayValid;
let demoFieldTwoValid = this.state.demoFieldTwoValid;
let prioritiesArray = this.state.prioritiesArray;
let demoFieldTwo = this.state.demoFieldTwo;
switch (fieldName) {
case "prioritiesArray":
prioritiesArrayValid = value.length > 0;
fieldValidationErrors.prioritiesArray = prioritiesArrayValid
? ""
: " is required";
this.setState(
{
prioritiesArray: prioritiesArray,
prioritiesArrayValid: prioritiesArrayValid
},
() => {
return {
prioritiesArray: value,
prioritiesArrayValid: prioritiesArrayValid
};
}
);
break;
case "demoFieldTwo":
demoFieldTwoValid = value.length > 0;
fieldValidationErrors.demoFieldTwo = demoFieldTwoValid
? ""
: " is required";
console.log("...demoFieldTwo", demoFieldTwo);
this.setState(
{ demoFieldTwo: demoFieldTwo, demoFieldTwoValid: demoFieldTwoValid },
() => {
return {
demoFieldTwo: value,
demoFieldTwoValid: prioritiesArrayValid
};
}
);
break;
default:
break;
}
this.setState(
{
formErrors: fieldValidationErrors
},
this.validateForm
);
}
validateForm() {
let formValid = this.state.formValid;
this.setState({ formValid: formValid }, () => {
return {
formValid:
this.state.prioritiesArrayValid && this.state.demoFieldTwoValid
};
});
// console.log("this.state.formValid", this.state.formValid);
}
handleUserInput(e) {
const name = e.target.name;
const value = e.target.value;
localStorage.setItem(name, value);
this.setState({ [name]: value });
}
validateFields() {
document
.getElementById("form")
.querySelectorAll("[required]")
.forEach(el => {
this.validateField(el.name, el.value);
});
}
submitForm(e) {
e.preventDefault();
this.validateFields();
if (this.state.formValid) {
console.log("FORM VALID");
} else {
console.log("this.state.formErrors", this.state.formErrors);
}
}