Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  138] [ 3]  / answers: 1 / hits: 131270  / 9 Years ago, wed, april 8, 2015, 12:00:00

I am trying to find the best way to remove an element from an array in the state of a component. Since I should not modify the this.state variable directly, is there a better way (more concise) to remove an element from an array than what I have here?:



  onRemovePerson: function(index) {
this.setState(prevState => { // pass callback in setState to avoid race condition
let newData = prevState.data.slice() //copy array from prevState
newData.splice(index, 1) // remove element
return {data: newData} // update state
})
},


Thank you.



updated



This has been updated to use the callback in setState. This should be done when referencing the current state while updating it.


More From » reactjs

 Answers
5

The cleanest way to do this that I've seen is with filter:



removeItem(index) {
this.setState({
data: this.state.data.filter((_, i) => i !== index)
});
}

[#67143] Tuesday, April 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackenzihannal

Total Points: 548
Total Questions: 96
Total Answers: 96

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;