Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  105] [ 2]  / answers: 1 / hits: 19660  / 5 Years ago, sat, june 8, 2019, 12:00:00

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.


More From » reactjs

 Answers
8

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);

[#52026] Friday, May 31, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yulissamirandah

Total Points: 493
Total Questions: 115
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
yulissamirandah questions
Fri, Jun 17, 22, 00:00, 2 Years ago
Wed, Aug 26, 20, 00:00, 4 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;