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

234
Vistas
this.state returning different values in console.log and display

I have a project that uses a class component to count the number of button presses. I got it to work, but when I console.log the count value, it returns a number one lower than the number displayed, even though they are using the same reference. I expected them to be the same number.

class ButtonCounter extends React.Component {
            constructor() {
                super()
                this.state = {
                    count: 0
                }
            }
            counter = 0
            getCount = () => {
                console.log('giving count')
                return this.counter
            }
            setCount = (amnt) => {
                this.counter += amnt
                this.setState({
                    count: this.counter
                })
                console.log(this.state.count) // returns -1 than the displayed value
            }
            render(){
                return(
                    <div>
                        <button onClick = {() => this.setCount(1)}>{this.state.count}</button>
                    </div>
                )
            }
        }

image of the code in browser

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As stated in react docs

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied

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

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