Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda