Reputation: 239
How to clear the existing data in react state variable (Array) and assign another array to it. I have try below thing but it doesn't works.
itemsChanged(items) {
this.setState({item : []}) //item is my state variable
this.setState({item : items})
console.log("ITEMS : ",this.state.item) //this will not print the updated value
}
Thanks in advance
Upvotes: 0
Views: 12439
Reputation: 1
setState
is an async function,if you are writting the code as that:
this.setState({xxState})
console.log(this.state.xxState)
The program will execute the console.log
first,so you should write as that:
this.setState({xxx},()=> {
console.log(this.state.....)
})
And it will be work well.
Upvotes: 0
Reputation: 137
One thing you should understand about setState
is that it works asynchronously. If you try to console.log
the state directly after calling setState
, you won't see any changes yet.
You also don't have to clear out the array by calling setState
with an empty array--you can just replace the current array with the new array.
this.setState({ items: newItems });
If you want to log the change, I'd suggest trying to do it in the component's componentShouldUpdate
method.
Upvotes: 0
Reputation: 2294
As they describe:
setState(updater, [callback])
so that may suggest it is not a synchronous operation.
Use:
itemsChanged(items) {
var me = this;
me.setState({item : items}, function(){
console.log("ITEMS : ", me.state.item);
});
}
Upvotes: 0
Reputation: 3333
setState
is an async method. So, when you print it on console, It still can be updating. You can use console log before return render.
...
render(){
console.log("ITEMS : ",this.state.item);
return (<div>...</div>)
}
...
Upvotes: 0
Reputation: 1478
According to React's docs
React may batch multiple setState() calls into a single update for performance.
If you want to check your state value after setState
, you should do like:
this.setState({item : items}, () => console.log(this.state.item));
Upvotes: 1
Reputation: 37584
You don't need to assign an empty array first. Just pass the new array to it. The only reason why it's not working is that setState
is an asynchronous call. Use it like this
this.setState({item : items}, () => console.log("ITEMS : ",this.state.item) )
Upvotes: 3