0

I have an array of boolean as a state in my component. If it is false, I want to set it as true.

this.state = {
       checkedPos: []
}

handleChange(index, reaction) {
   if (!this.state.checkedPos[index])
   {
      this.state.checkedPos[index] = true;
      this.addReaction(reaction);
      this.forceUpdate();
   }
}

It works, but the only problem I encounter is that it show this warning:

Do not mutate state directly. Use setState()

So I tried changing it and putting it like this:

this.setState({
 checkedPos[index]: true
})

But it does not compile at all.

1
  • Is handleChange bound to have component as this inside function ? Then follow @Tholle `s answer below. Commented Mar 10, 2019 at 16:12

2 Answers 2

2

One solution would be to map the previous array in your state. Since you should never modify your state without setState I will show you how you can use it in this solution :

handleChange(index) {
    this.setState(prev => ({
        checkedPos: prev.checkedPos.map((val, i) => !val && i === index ? true : val)
    }))
}

Here, map will change the value of your array elements to true only if the previous value was false and if the index is the same as the one provided. Otherwise, it returns the already existing value.

You can then use the second argument of setState to execute your function after your value has been updated :

handleChange(index) {
    this.setState(prev => ({
        checkedPos: prev.checkedPos.map((val, i) => !val && i === index ? true : val)
    }), () => {
        this.addReaction(reaction);
    })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Iterating throught the array like you did (without binding function) makes the warning go away. I used the first example btw
2

You can use the functional setState for this.

this.setstate((prevState) => ({
    const checkedPos = [...prevState.checkedPos];
    checkedPos[index] = true
    return { checkedPos };
}))

2 Comments

this will not change checkedPos, this will set a new property to state checkedPos[index] <-- whatever value of this will become key
Yeah, you are right. Will probably have to spread the whole array and overwrite the changed index

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.