Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setState to update an array in React?

I need to update an array in the state of my component in React. I've seens several topic with this question, but so far all of them are adding new items to the array with the spread operator, but I need to add OR remove items on a callback like this:

  handleCheck (newStatus, isChecked) {
    this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
  }

But the problem here is that it didn't work for status where the isChecked boolean comes false to remove them from the array

What is the best way to add or remove items from that array, hopefully with spread operator?

Thanks

like image 314
Leonardo Uribe Avatar asked Feb 18 '26 12:02

Leonardo Uribe


1 Answers

try to use the .filter to remove the element. Remember to duplicate the array (using [...array] syntax) before using .filter, to don't change the original array:

handleCheck (newStatus, isChecked) {
    let newArray = isChecked? // if isChecked is true
        [...this.state.filterStatus, newStatus] : // add element
        [...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
    this.setState({ filterStatus: newArray})
}
like image 136
Murilo Cruz Avatar answered Feb 20 '26 02:02

Murilo Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!