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]
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?
This question is related to
javascript
reactjs
state
setstate
I had the same situation with some convoluted code, and nothing from the existing suggestions worked for me.
My problem was that setState
was happening from callback func, issued by one of the components. And my suspicious is that the call was occurring synchronously, which prevented setState
from setting state at all.
Simply put I have something like this:
render() {
<Control
ref={_ => this.control = _}
onChange={this.handleChange}
onUpdated={this.handleUpdate} />
}
handleChange() {
this.control.doUpdate();
}
handleUpdate() {
this.setState({...});
}
The way I had to "fix" it was to put doUpdate()
into setTimeout
like this:
handleChange() {
setTimeout(() => { this.control.doUpdate(); }, 10);
}
Not ideal, but otherwise it would be a significant refactoring.
setState is asynchronous. You can use callback method to get updated state.
changeHandler(event) {
this.setState({ yourName: event.target.value }, () =>
console.log(this.state.yourName));
}
I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me
const [state, setState] = useState({
foo: "abc",
bar: 123
});
// Do this!
setState(prevState => {
return {
...prevState,
foo: "def"
};
});
setState(prevState => {
return {
...prevState,
bar: 456
};
});
The setState()
operation is asynchronous and hence your console.log()
will be executed before the setState()
mutates the values and hence you see the result.
To solve it, log the value in the callback function of setState()
, like:
setTimeout(() => {
this.setState({dealersOverallTotal: total},
function(){
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});
}, 10)
In case of hooks, you should use useEffect
hook.
const [fruit, setFruit] = useState('');
setFruit('Apple');
useEffect(() => {
console.log('Fruit', fruit);
}, [fruit])
Using async/await
async changeHandler(event) {
await this.setState({ yourName: event.target.value });
console.log(this.state.yourName);
}
just add componentDidUpdate(){}
method in your code, and it will work.
you can check the life cycle of react native here:
The setstate is asynchronous in react, so to see the updated state in console use the callback as shown below (Callback function will execute after the setstate update)
The below method is "not recommended" but for understanding, if you mutate state directly you can see the updated state in the next line. I repeat this is "not recommended"
As well as noting the asynchronous nature of setState, be aware that you may have competing event handlers, one doing the state change you want and the other immediately undoing it again. For example onClick on a component whose parent also handles the onClick. Check by adding trace. Prevent this by using e.stopPropagation.
Source: Stackoverflow.com