0

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_;
};
Octavian
  • 21
  • 4
  • `errors` is a local const. It will never change. The purpose of `setErrors` is to cause the component to rerender, and while that new render will create new local variables, those aren't accessible in the previous render's code. If you need to know what was returned by `validatePassword`, perhaps call it before setErrors and assign it to a local variable, as in `const newErrors = validatePassword(); setErrors(newErrors); /* do stuff with newErrors */` – Nicholas Tower Oct 13 '21 at 19:29

0 Answers0