I am trying to add and delete an obect from an array, I have been able to figure out the add object part, but the deletion is not working. I have used filter() but it did nothing. Now I am using splice, it works but it deletes the first element, instead of the selected item. below is a sample code, and I have shown only the functions for better clarity.
handleDelete(item) {
this.setState(({ list}) => {
const newList = [...list];
newList.splice(item.key, 1);
console.log('deleted', newList);
return { list: newList };
});
}
handleAdd() {
const { firstname, lastname, email, phone} = this.state;
const ID = uuid();
const newItemObject = {
key: ID,
firstname: firstname,
lastname: lastname,
email: email,
phone: phone,
image: null,
};
this.setState(prevState => ({
list: [...prevState.list, newItemObject]
}));
}
I would like to
The item's key and index in the array are probably not the same. If the item is in the array, you can use Array.indexOf()
to find it's index, and splice it out:
handleDelete(item) {
this.setState(({ list }) => {
const newList = [...list];
const index = newList.indexOf(item);
newList.splice(index, 1);
return {
list: newList
};
});
}
Or if you want to use Array.filter()
, check if the key of of current element (o
) is different from that of item
:
handleDelete(item) {
this.setState(({ list }) => ({
list: list.filter(o => o.key !== item.key)
}))
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments