Home > OS >  Unable to update state - react-native
Unable to update state - react-native

Time:12-21

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

Can anyone see what I am doing wrong, please? Thanks

    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
        }
      };

    }

CodePudding user response:

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
    }
  };

}

CodePudding user response:

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'});
        }
      };
    
    }
  • Related