1

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

6
  • 1
    what are you trying to update ? Are you making the array empty? Commented Nov 18, 2020 at 15:17
  • @WillJenkins How do you know that's not in the constructor? I think it is the inner of setState. Commented Nov 18, 2020 at 15:19
  • @BrianThompson - it tells you to "Use setState()", which you are doing Commented Nov 18, 2020 at 15:19
  • 1
    But there is also a direct assignment to this.state.xx which seems more likely to be the problem. Commented Nov 18, 2020 at 15:20
  • 1
    @UKS Yes, I just want to make to make the array empty Commented Nov 18, 2020 at 16:02

2 Answers 2

2

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]
  }
}));
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.