I'm changing a state in React based on a previousState. Basically I'm removing an item from an array of items and I want the best simplest way.
This works perfectly, but maybe not the best practice?
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(
previousState => {
const { items } = previousState;
items.splice(index, 1);
return {
items
};
}
);
};
Is there any issues regarding this code that concerns mutability etc in React way of reworking previousState? Is previousState
mutable, and even if so, is it OK to do so?
Otherwise what do you consider best way of handling such case?
Method splice modifies original array - so this is not the way you need.
Instead you can filter out an unneeded item. Please read more about filter method which creates a new array.
Also you don't need to create a variable for the whole state. Instead you can use destructuring:
handleItemsRemove = (id, index) => {
if (index === -1) {
return;
}
this.setState(({items}) => ({
items: items.filter((item, itemIndex) => index !== itemIndex),
}));
};