I have a React application (like Netflix) that displays movies thumbnails on the homepage.
When you click on a thumbnail, a modal window appears where you can click on a button to add the movie to your Watchlist. These movies will be saved in local storage and if you go to the component "Watchlist", you can see all the favorite movies displayed.
Here is the code that handles the click (this function is stored in the Context) (I don't use useState because a re-render would trigger a change in the background of the app):
const storageArray = [];
const handleWatchlist = (objectData) => {
let index = storageArray.indexOf(objectData);
if (index === -1) {
storageArray.push(objectData);
} else {
storageArray.splice(index, 1);
}
localStorage.setItem('currentWatchlist', JSON.stringify(storageArray));
const retrieveData = JSON.parse(localStorage.getItem('currentWatchlist'));
console.log(retrieveData);
};
It works perfectly fine on the homepage. HOWEVER, in the watchlist component, if I click on a thumbnails, and then click on the button to remove the item from the storage, here is what happens:
Example: 1 movie stored in localStorage, before I click:
Inside of the watchlist component, after I click on the button, to remove it from the storage and the component:
When I click on the button, instead of removing it the element, it doesn't consider it a duplicate and so add a new object to the Local Storage (which is removed if I click again).
How can I make sure that when I click on the favorite button in the Watchlist component, the storage is updated correctly and the movie removed from the component?
Thank you for your help.
You're starting with an empty array:
const storageArray = [];
And then check if the objectData
is in the array or not with:
storageArray.indexOf(objectData);
This will never find the existing item in the localStorage
because you never read from localStorage
. What you need to do is, when handleWatchlist
is called:
localStorage
and parse to a listobjectData
It'll be something like:
const handleWatchlist = (objectData) => {
let storageArray = JSON.parse(localStorage.getItem("currentWatchlist"));
let existingItem = storageArray.find(item => item.id === objectData.id);
if (existingItem) {
let result = storageArray.filter(item => item.id !== objectData.id);
} else {
let result = [...storageArray, objectData];
}
localStorage.setItem("currentWatchlist", JSON.stringify(result));
};