Why is my recipe box deleting the opposite recipe?

Here is my codepen:

It seems like everything is working, even the local storage. I only have 2 problems left. First of all, when I try to delete an element, for whatever reason the program deletes the other element (I’ve looked over the code for an hour and can’t find the index issue), and secondly, the program doesn’t allow for there to 0 recipes available. I suppose this is because when I try to delete the last recipe, it tries to delete an index that doesn’t exist. Please help.

Hi - I briefly looked over your code (as I’m on my iPhone :slight_smile: and I remember from when I did my Recipe Box, I had the very same issue.

When there’s only one recipe left in the array, the index of course is 0. So when we use the .splice() method, we have to give it an index to start at and a delete count.

In order to delete the last recipe, the splice method will have to start at -1…so that if there is one recipe left in the array (with the recipe index being 0), it will remove that one recipe.

Hope that makes sense :grinning:

Splice method returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

So when you do

var newArr = this.state.recipes.splice(index, 1);

newArr will actually equal to deleted element.

By the way splice changes the contents of array and therefore mutates your state. Use slice or filter to delete an element instead.

@prohorova @CandiW Thank you!

1 Like