Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!