I am trying to update my state so that a nested array gets emptied but the rest of the state stays the same.
My state object looks like:
this.state = { data: { type: "FeatureCollection", features: [1,2,3,4] } }
And I the closest I get to working is:
this.setState(prevState => ({ data: [...prevState.data, (this.state.data.features.length = 0)] }));
The console warning I get with this approach is:
Do not mutate state directly. Use setState() react/no-direct-mutation-state
But how else is this possible?
Many thanks 🙂
Advertisement
Answer
The first problem I see with your code is you’re changing data
from an object to an array. So it should as least be
this.setState(prevState => ({ data: {...prevState.data, (this.state.data.features.length = 0)} }));
Then you’re still mutating state by doing this.state.data.features.length = 0
, so to fix that, you need to update that array immutably:
this.setState(prevState => ({ data: { ...prevState.data, features: [] // Or whatever you need your new array to be } }));
So say you wanted to add another element to the end, you could do:
this.setState(prevState => ({ data: { ...prevState.data, features: [...prevState.data.features, 5] } }));