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

99
Visualizações
React cannot set variable inside onClick function

I am trying to set a variable inside an onClick event. I am setting the error messages into the variable.

const handleEdit = (e) => {
        e.preventDefault();

         if (edit_user.email == "") {
             setEditUserError({ email: "Please enter an email!" })
        }

        if (edit_user.company == "") {
           setEditUserError({ ...edit_user_error, company: "Please enter company!" })
       }

And I am showing the error in the form like <span className="text-danger">{edit_user_error.company}</span>

The problem is that when all the fields are empty and when I click the button only the last message is shown. When I make one field empty, and then click the submit button it is working correctly. I tried console.log(edit_user_error) but it is showing empty. What am I doing wrong? Please help

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is because of batched state updates. React will try to reduce the renders by minimizing the state updates. You can use functional state update to fix this:

if (edit_user.email == "") {
  setEditUserError({ email: "Please enter an email!" });
}

if (edit_user.company == "") {
  // this callback gets executed only when previous state updates are done
  setEditUserError((prev) => ({ ...prev, company: "Please enter company!" }));
}

To clear the errors when fields are valid:

const getErrors = () => {
  return {
    ...(!edit_user.email ? { email: "Please enter an email!" } : {}),
    ...(!edit_user.company ? { company: "Please enter company!" } : {}),
  };
};

const handleEdit = (e) => {
  e.preventDefault();

  setEditUserError(getErrors());
};
about 4 years ago · Juan Pablo Isaza Relatório

0

React state updates are async, which means they won't run right away. So when running multiple setState to the same state, you can't expect the state from the first setState call to be update it before the second setState call happens.

In short, React is ignoring your earlier setState calls because they happen one after another.

The solution is to put the update into a single call:

    const handleEdit = (e) => {
        e.preventDefault();
         
        let errors = {};

         if (edit_user.email == "") {
             errors.email = "Please enter an email!"
        }

        if (edit_user.company == "") {
           errors.company = "Please enter company!"
       }

      // and then we call state with all the values, only once
      setEditUserError(errors);

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