I have a delete function that looks like this:
this.deleteItem = item => event => {
const { res, selectedItems } = this.state;
res.splice(res.indexOf(item), 1);
selectedItems.splice(res.indexOf(item), 1);
this.setState({
res
});
};
Here, the res
is the list of items displayed on the page, and selectedItems
is a list of which of those items are selected. When an item from res
is deleted, selectedItems
should be updated to remove the index of that item from the list.
Whenever I try to delete a specific item however, it just deletes the last item added to the array, rather than the item that corresponds to the index of the target clicked. Something must be going on with the way it's being indexed, but I've been having trouble identifying the source.
I've also tried as referenced here, but this didn't work since I need to take in item
as a parameter.
What would be a good way to go about this?
Thank you very much.
EDIT: Changed the function to look like @HMK's response. After an item is deleted, the output of console.log(res)
in the render method is an array of objects which has the form:
res
(9) […]
0: Object { id: 0, name: "a", description: "description of a", … }
1: Object { id: 2, name: "b", description: "description of b", … }
2: Object { id: 3, name: "c", description: "description of c", … }
3: Object { id: 4, name: "d", description: "description of d", … }
4: Object { id: 5, name: "e", description: "description of e", … }
5: Object { id: 6, name: "f", description: "description of f", … }
6: Object { id: 7, name: "g", description: "description of g", … }
7: Object { id: 8, name: "h", description: "description of h", … }
8: Object { id: 9, name: "i", description: "description of i", … }
length: 9
<prototype>: Array []
The output of console.log(JSON.stringify(item,undefined,2));
in the deleteItem
function is the object that is deleted from the array.
e.g.:
{
"id": 10,
"name": "j",
"description": "description of j",
"icon": "jIcon",
"selected": false
}
When all items on the page are selected, the output of console.log("selecteditems:", JSON.stringify(selectedItems))
:
selecteditems: [0,1,2,3,4,5,6,7,8,9,10]