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!!
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)})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With