'How to use setState() in React to blank/clear the value of an array
I am trying to clear an array, but I'm having trouble.
this.setState({warnErrorTypes:[]})
I'm not sure if I am dealing with a race condition, or what the specific issue is, but I can see that the value of my array is consistently wrong in the case that I need to reset its value to [].
How does one replace an array that contains [1,2] with [] then subsequently [3] where the following are true:
- this.state.warnErrorTypes is an Array which starts out with []
- Based on condition, 2 is pushed in Array
- Based on condition, 1 is pushed in Array.
- Based on condition, 3 is NOT pushed in Array
- Pause. User interacts with UI
- Array is blanked:
this.setState({warnErrorTypes:[]}) - Based on condition, 2 is NOT pushed in Array
- Based on condition, 1 is NOT pushed in Array
- Based on condition, 3 is pushed in Array.
The result of the logic above is always [2,1,3], when I expect it to be [3].
Solution 1:[1]
Option 3, as mentioned by Anders Ekdahl:
moo () {
this.setState(state => ({
myarr: []
}));
// ...
if (weShouldAddAThree) {
this.setState(state => ({
myarr: [ ...state.myarr, 3 ] // like push but without mutation
}));
}
}
This pattern is useful if you need to refer to the previous existing state when you perform your state update. I'm not sure if you really need the previous state in your example, but I will explain this pattern as if you did.
The merge operation we provide to setState is always applied asynchronously, at some point in the future, at React's discretion. When the setState() function returns, our operation has not been applied, it has only been queued.
Therefore we should never use this.state in our state updater, because that might be out of date: an old copy of the state. If we need to know the previous state, we should receive the state argument in the function we pass to setState, and use that.
Solution 2:[2]
You can as well use this to clear array:
this.state.your_array.length = 0;
setState({your_array});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | joeytwiddle |
| Solution 2 |
