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?
setItems()
that is broken, andfilter()
works fine? I'm not sure, but a sandbox would help.key
for the mapped JSX.