Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React filter method without mutating state

My current state has this:

state = { items : [{id: 1, text: 'test words'}, {id: 2, text: 'another test'}]

Here's my function to remove objects from the array, trying to avoid mutating state.

handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState(prevState => ({
    items: prevState.items = newArray
  }))

  console.log('handle remove runned', passedInId, myItems, newArray)

}

It works perfectly but would like to know if it's not anti-pattern before moving on with my life

Many THANKS!!

like image 988
Clay_F Avatar asked Dec 23 '22 19:12

Clay_F


1 Answers

Your function is almost right, and you have the right idea. You don't need to use the version of setState that takes a mutator function in your case, instead just do:

handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState({
    items: newArray
  })

  console.log('handle remove runned', passedInId, myItems, newArray)

}

To be honest, this is simple enough that a one liner will do:

handleRemove(passedInId) {
  this.setState({items: this.state.items.filter(item => item.id !== passedInId)})
}
like image 111
TomW Avatar answered Dec 31 '22 12:12

TomW