'Unable to update state while using React Native

I am trying to get to grips with the React hook useState. At the moment I am unable to update the state of my errors object, a little unsure of where I am going wrong. The idea here is to store the error messages in a signup form.

In this example, a user submits an empty first name, but the error object always remains empty. What am I doing wrong?

    export const SignUp = () => {

      const [errors, setErrors] = useState({});

      const validateFirstName = () => {
        if (formData.firstName === undefined) {
          setErrors({...errors, firstName: 'First Name is required'});
          console.log({errors}); // When condition is met errors is still an empty object
        }
      };

    }


Solution 1:[1]

Try with this, I added comments in the code.

export const SignUp = () => {

  const [errors, setErrors] = useState({});
  console.log({errors}); // try with this
  const validateFirstName = () => {
    if (formData.firstName === undefined) {
      setErrors({...errors, firstName: 'First Name is required'});
      console.log({errors}); // at this point, it is normal to have an empty errors, cause your component did not re-rendered yet
    }
  };

}

Solution 2:[2]

What you are doing is basically correct. The state just has not changed yet when you call the console.log(). If you want to do something when your state changes, you can use the useEffect hook and pass the state as the second parameter. When you use the errors state in your jsx code somewhere it will work as you'd expect it to work.

    export const SignUp = () => {
    
      const [errors, setErrors] = useState({});

      useEffect(() => {
        console.log(errors);
      },[errors])
    
      const validateFirstName = () => {
        if (formData.firstName === undefined) {
          setErrors({...errors, firstName: 'First Name is required'});
        }
      };
    
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Andreas Jagiella