Wisdom1
Wisdom1

Reputation: 129

How to update nested array in React state?

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 :)

Upvotes: 1

Views: 152

Answers (2)

Brian Thompson
Brian Thompson

Reputation: 14355

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]
  }
}));

Upvotes: 2

Sarun UK
Sarun UK

Reputation: 6736

You should update the state like this. data in the state is an object, not an array.

this.setState(prevState => ({
    data: {...prevState.data, features: [] }
}));

Upvotes: 1

Related Questions