patternjavascriptreactCritical
React setState not updating state
Viewed 0 times
setstateupdatingreactstatenot
Problem
So I have this:
however
any obvious or should I post more code?
let total = newDealersDeckTotal.reduce(function(a, b) {
return a + b;
},
0);
console.log(total, 'tittal'); //outputs correct total
setTimeout(() => {
this.setState({ dealersOverallTotal: total });
}, 10);
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); //outputs incorrect total
newDealersDeckTotal is just an array of numbers [1, 5, 9] e.g.however
this.state.dealersOverallTotal does not give the correct total but total does? I even put in a timeout delay to see if this solved the problem.any obvious or should I post more code?
Solution
setState() is usually asynchronous, which means that at the time you console.log the state, it's not updated yet. Try putting the log in the callback of the setState() method. It is executed after the state change is complete:this.setState({ dealersOverallTotal: total }, () => {
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});Code Snippets
this.setState({ dealersOverallTotal: total }, () => {
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});Context
Stack Overflow Q#41446560, score: 322
Revisions (0)
No revisions yet.