I'm trying to learn React and build a form that sends data to a Rest API and I have some problems in implementing user-side validation. I have to update my errors state and I'm using a function to do this, validatePassword. In the on submit function, I have to change the state of the errors variable to what the validatePassword function is returning. The only problem is that it doesn't. Any help?
const [password, setPassword] = useState("");
const [secondPassword, setsecondPassword] = useState("");
const [errors, setErrors] = useState({});
function handleSubmit(event) {
setErrors(() => validatePassword());
console.log(errors);
//Check if any errors
if (Object.keys(errors).length === 0) {
//console log ok
event.preventDefault();
sendRegisterRequest();
setTimeout(()=>{history.push('/login')}, 2000)
} else {
//show errors
event.preventDefault();
setPassword('');
setsecondPassword('');
console.log(errors);
}
};
function validatePassword() {
let errors_ = {}
if (password.length < 6) {
errors_['password'] = 'Password has to be longer than 6 characters';
}
else if (password !== secondPassword) {
errors_['password'] = 'Passwords do not match';
}
else {
console.log(errors_);
}
console.log(errors_);
return errors_;
};