Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda