React - State array deleting last item in array instead of specified index

Viewed 2312

I have an array state filled with objects called items:

    const [items, setItems] = useState([{name: "", toppings: []}])

However when I try to delete a specified index with this function:

const removeItem = (index) => {
    setItems(items.filter((item, i) => i !== index))
    areItemsCompleted()
}

It works when I print the elements to the console outside of the function, however the item is not rendering properly. It only removes the last element of the array from the jsx but the items array has the correct values. I read somewhere that react only checks for changes in state shallowly so it does not check the content of the object it is deleting. However, I am unsure as to why it shows up in the console that items have the correct value but the components arent rendering the correct data. (Instead it renders the same data except for the last element in items).

I have tried multiple ways of deleting elements from my array such as

const removeItem = (index) => {
    let arr = [...items]
    arr.splice(index, 1)
    setItems(arr)
    areItemsCompleted()
}

How would I delete an element from my array full of objects and render the proper data?

2 Answers

So I was using the array index as the key prop of the component, but that doesn't work when deleting an item in the array.

React doesn't know which key to delete, as the array index will still exist even after that particular element has been deleted.

Solution

Use a unique key for each element in the array. Something like id which react can see has been deleted.

It's hard to guess;

Check, may be you are re-setting items somewhere later;

Plus functional form is safer: setItems(lastItems=>lastItems.filter((item, i) => i !== index))

Related