Reputation: 998
**
I have a TextInput and two buttons which are responsible to increment or decrement the value of that TextInput. Using setState I am achieving it. Everything is fine but after setState when I am consoling the value it is showing me the previous value, but in TextInput I am getting the updated value. The code is the following:-
**
state = {
cartItems:[
{
id:1,
count:0
},
{
id:2,
count:0
},
],
}
changeQuantity = (productId,action)=>{
this.setState(prevState=>{
return{
cartItems:prevState.cartItems.filter(single=>{
if(single.id==productId){
if(action==='plus'){
single.count++;
}
if(action==='minus' && single.count>0){
single.count--;
}
}
return single;
})
}
})
console.log(this.state.cartItems.find(single => single.id === productId).count)
/*This gives the previous value not the updated value*/
}
Why is this happening and what is the proper way to get the updated value??
Upvotes: 0
Views: 209
Reputation: 2205
setState is asynchronous. The place where you have written the console.log will still have previous value hence it will show you old value. Try adding console in setState completion block to print the updated value of state.
this.setState({
// update your state here
}, () => {
console.log('Updated value ');
});
Upvotes: 4
Reputation: 1357
It you do a console to next line after setState has been called it will log only previous state. I don't know why the behaviour exists. Try logging it in componentDidUpdate.
Upvotes: 1