Reputation: 102
I am learning React and in one of the answer, I have seen the splice method is being used while deleting an item from the array. Link to the solution : Delete item from state array in react
To remove an element from an array, just do:
array.splice(index, 1); In your case:
removePeople(e) {
var array = [...this.state.people]; // make a separate copy of the array
var index = array.indexOf(e.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({people: array});
}
},
Expected: As in many other blogs, we have used the filter method to delete the items from the list. why the answer is getting upvoted and we are not using filter method here ?
Upvotes: 3
Views: 5141
Reputation: 8947
There are no rules such as use this method for that and that method for this. However, there are two conditions to be met to ensure that React is aware of changes to state.
setState
to update stateThe accepted answer you have linked meets both these requirements. The key line is,
var array = [...this.state.people] // make a separate copy of the array
Note the comment. The orginal poster has made it clear that he is creating a new reference to the array by using the spread syntax. The splice operation he performs later on is on this new array, it does not matter what operation he performs later on, React will call the render method at least once once when the new array is set as part of state.
Why filter?
Filter filters an array by a predicate and returns a new array object with the results. In some situations, this might be more flexible and convenient to use, but it has completely different behaviour. Splice allows for the precise removal of a contiguous block of elements by index whereas filter removes all elements that do not match the predicate.
The decision to use which is upto you based on what's best for the use case. React will re-render as long as the above conditions are met.
Note: In the situation presented, filter would be the performant choice as it only loops over the array once. The splice operation requires, spread and indexOf
prior to it which leads to multiple enumerations over the array.
Upvotes: 3