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

133
Visualizações
Confusion with how setState works

I am confused with how setState works.

Here is a portion of my code:

handleBarsChange(value) {
  this.setState({numberOfbars: value});
  this.resetArray();
}

apparently, when the resetArray() function executes and tries to access the this.state.numberOfbars state variable, setState hasn't updated the value yet.

I want some explanation on how and where should the setState be executed and when can i expect to see the change.

Thank you!

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

0

setState is asynchronous. It has a second callback argument that can be used to run code after a state transition. This isn't always the best approach, but with the very narrow example provided, it's hard to say.

this.setState({numberOfBars: value}, () => { this.resetArray() })

From the react docs:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

https://reactjs.org/docs/react-component.html#setstate

about 4 years ago · Juan Pablo Isaza Relatório

0

The fact is that setState() function is async so even if you run code after you call it, some state may not be updated yet.

The solution is implement a callback when the state was updated succesfully (setState(<state>, <callback>)), for example:

handleBarsChange(value){
    this.setState({numberOfbars: value}, () => {
        this.resetArray();
    });
}
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