I’m building a movie watch list that stores movies in my local storage, and removes them. Here are the two CodePens for my code, one which searches & adds:
https://codepen.io/vanessalearnsjavascript/pen/vYVJPgm?editors=0011
And the other which is the "Watch List" page that removes:
https://codepen.io/vanessalearnsjavascript/pen/YzJEQEW?editors=0011
removeMovieButton.addEventListener("click", function() {
watchList.splice(watchList.indexOf(movie), 1);
movieDiv.parentNode.removeChild(movieDiv);
localStorage.removeItem("movie" + watchList.indexOf(movie));
});
On the WatchList page, I have a "Remove Movie" button rigged up that removes the movie from the array and from the DOM, but the local storage of it does not work. Here is the removeMovie button, with the local storage line that is not executing. I can press the button and it removes the item from the array and the DOM, but when I have the local storage open, it remains.
Can anyone explain how I can fix this and why this is happening? Thanks.
3
Answers
you have just to change the execution orders, so replace this
by
Explanation: you are deleting the movie from the array then you are getting a wrong index of the "already" deleted item to remove it from localStorage, that’s why it did not work for you .
Why does it not work? You remove the item and then you try to find that item once again. Are you going to find it after it is removed?
Now you can store the index into variable, but when you remove the index, all of the other entries move down one. So that means
movie4
in the array would be at index 3, not 4. So you would have to adjust all of your local storage keys.Just store the array!
when you need the watch list, read it
basically
localStorage
is a global variable that doesn’t disappear when the browser is reloaded. and can also be for communication between tabs