Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Javascript / React - Remove specific item from Local Storage on click when rendered in another component

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: enter image description here

Inside of the watchlist component, after I click on the button, to remove it from the storage and the component: enter image description here

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

  • Read from the localStorage and parse to a list
  • Find an existing item within that list by a unique key from objectData
    • If it's there, remove it
    • if not, add it

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));
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda