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

302
Vistas
React JS onChange function of Material UI 'number' TextField uses previous value

I have an onChange function on this element:

<TextField id="rowinput" type="number" 
           defaultValue={this.defaultRows} // defaultrRows = 1
           inputProps={{ min: "1", max:"5"}}
           onChange={this.handleRows}>
</TextField>

This is the function:

handleRows = ev => {
        let newrows = ev.target.value;
        let newcount = newrows * this.state.cols;
        this.setState( {rows: newrows, panelcount: newcount} )
        console.log("Row Count: " + this.state.rows);
        console.log("Total Count: " + this.state.panelcount);
}

What this should do is take the value of the input field when the up and down arrows are clicked, and update the state. However, I've found that when the console statement in the handler prints its result, the number used is one step behind.

As you can see, on page load it starts with a default value of 1 (as does the cols value it is referencing), and so when the up arrow is clicked, the value changes to 2 and it should print out:

Row Count: 2

Total Count: 2

When I print the temporary variables it prints 2 and 2, but when I use the state call here, it prints 1 and 1. Here for example, I increased the value up to 5, and you can see the console never logged higher than 4:

enter image description here

enter image description here

Is the state update called asynchronously? How can the temporary variables be correct but calling this.state.rows is one iteration behind?

Any help would be greatly appreciated

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

0

When using setState the state is not actually updated until the next render. Your console log is in the same function and occurs before the re-render after state is updated. If you were to do the console.log outside of the function you will see that the state is updated.

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