title: React useState in form
body: <p>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?</p>
  <pre><code>const [password, setPassword] = useState(&quot;&quot;);
  const [secondPassword, setsecondPassword] = useState(&quot;&quot;);
  const [errors, setErrors] = useState({});
  
  function handleSubmit(event) {
  
    setErrors(() =&gt; validatePassword());
    console.log(errors);
    
     //Check if any errors
    if (Object.keys(errors).length === 0) {
  
        //console log ok
        event.preventDefault();
        sendRegisterRequest();
        setTimeout(()=&gt;{history.push('/login')}, 2000)
                
    } else {
  
        //show errors
        event.preventDefault();
        setPassword('');
        setsecondPassword('');
        console.log(errors);
  
    }
  };
  
  function validatePassword() {
  
      let errors_ = {}
  
      if (password.length &lt; 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_;
  };
  </code></pre>