I have a state with validations like this:
this.state = {
email: '', pass: '',
errors: {
email: '', pass: ''
}
}
and when a user press a button, it validates the form like this:
onSubmit = (e) => {
e.preventDefault();
this.setState({errors: {pass: '', email: ''}});
const pass = this.state.pass.trim();
if(!isEmail(this.state.email)){
this.setState({errors: {...this.state.errors, email: 'Invalid Email.'}});
}
// return; - in this way email state error will be ok
if(pass.length < 6){
this.setState({errors:{ ...this.state.errors, pass: 'Password Invalid'}});
}
return console.log(this.state);
};
I am using ...
operator to append type of errors in the errors object. The problem is that, if the email is invalid and there is an error for the password the state is like this:
errors: {email: '', pass: 'Password Invalid'}
If I use return
before pass check, the email error state works normal.
I know that setState
is async, but how to append different values of deep state object ?