React setState does not update state

So, I have this:

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] , for example. however this.state.dealersOverallTotal does not give the correct value, but does total ? I even set a timeout delay to see if this resolved the problem. any obvious or should i post more code?

+20
source share
4 answers

setState() usually asynchronous, which means that while you are console.log state, it is not yet updated. Try putting the log in the callback to the setState() method. It is executed after the state change is completed:

 this.setState({ dealersOverallTotal: total }, () => { console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); }); 
+55
source

setState() takes time to change the value, and your javascript is asynchronous , and therefore your console.log() will be executed before setState changes the values ​​and therefore you will see the result.

To solve this problem, register the value in the callback function of setState as

 setTimeout(() => {this.setState({dealersOverallTotal: total}, function(){ console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); }); }, 10) 
+4
source

setState is asynchronous. You can use the callback method to get the updated state.

 changeHandler(event) { this.setState({ yourName: event.target.value }, () => console.log(this.state.yourName)); } 
+4
source

Source: https://habr.com/ru/post/1262228/


All Articles