Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

    }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

}
about 4 years ago · Juan Pablo Isaza Report

0

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'});
        }
      };
    
    }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!