Reputation: 534
I am trying to validate field when I click on submit button. This is how I defined my state.
const [values, setValues] = useState({
email: "",
password: "",
emailErrorMessage: "",
passwordErrorMessage: "",
errorMessage: "",
emailError: false,
passwordError: false,
rememberMe: false,
});
In submit method, this is how I am validating it.
if (values.email.length <= 0) {
setValues({
...values,
emailError: true,
emailErrorMessage: "Email field must not be empty"
})
};
if (values.password.length <= 0) {
setValues({ ...values, passwordError: true, passwordErrorMessage: "Password field must not be empty" });
}
For somehow it is only showing me error for password field. Although it is going through both the if conditions. Not sure how exactly I can Fix it.
Expected:- it should show error for both email and password.
Upvotes: 7
Views: 20528
Reputation: 676
Problem 1: The state update is an asynchronous process, so, in your case, you're updating the state for the first time by spreading the current state, then you're updating it for the second time, by spreading also the current state (not updated yet). As a result, the last state successfully updated (it's a gamble actually, with more luck for the second update) will be the actual nextState, that's why you encounter the password being updated only
Problem 2: Every state update triggers a re-render. You're updating the state twice (even though it's done wrong, but it's a fact), when you could do it just once (to have just one re-render).
A solution to solve both problems will be:
const newValues = {...values};
if (values.email.length <= 0) {
newValues.emailError = true;
newValues.emailErrorMessage = "Email field must not be empty";
};
if (values.password.length <= 0) {
newValues.passwordError = true;
newValues.passwordErrorMessage = "Password field must not be empty";
}
setValues(newValues);
Upvotes: 8
Reputation: 1431
@RaduNemerenco has a good answer but you can just add another if statement that checks for both conditions
if (values.email.length <= 0) {
setValues({
...values,
emailError: true,
emailErrorMessage: "Email field must not be empty"
})
};
if (values.password.length <= 0) {
setValues({ ...values, passwordError: true, passwordErrorMessage: "Password field must not be empty" });
}
if (values.email.length <= 0 && values.password.length <= 0) {
setValues({
...values,
emailError: true,
emailErrorMessage: "Email field must not be empty",
passwordError: true,
passwordErrorMessage: "Password field must not be empty"
})
};
Upvotes: -3