5

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
  • Is it possible to get a working sandbox demo with the minimal problem? I think there's too much going on here to automatically know the solution -- i.e., maybe it is setItems() that is broken, and filter() works fine? I'm not sure, but a sandbox would help. Jun 19, 2020 at 21:08
  • 3
    Sounds like you're using the array index as the key for the mapped JSX. Jun 19, 2020 at 21:12

2 Answers 2

4

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.

1
  • 1
    this solution solved my problem. I generated an id (use Math.random()) for each item and set it as key
    – Frank Wang
    Oct 20, 2021 at 8:23
2

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))

1
  • I just checked, and I am not re-setting the state somewhere else since the only other function in the method is to change a different state. I tried the code above and sadly it did not work. (It gave correct output in the console but did not render the components still) Jun 20, 2020 at 1:30

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.