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

204
Visualizações
localstorage setItem() is not working in some cases

I'm using react reducer to handle a request for a deleting an item from the list:

case 'REMOVE_ITEM': {
      let products = state.products!
      for( var i = 0; i < products.length; i++){ 
    
        if ( products[i].id === action.payload) { 
          products.splice(i, 1); 
        }
      }

      let result = {...state, products: products, productSelected: products[0]}
      localStorage.setItem('state', JSON.stringify(result))
      console.log(result)
      return { ...state, products: products, productSelected: products[0]}
    }

When I click the first item everything works great, but when I delete other items, my state updating and console.log(result) work fine, but there are no updates to localstorage, so I assume that setItem is not launching. I would greatly appreciate if someone could help me with this issue.

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

0

In React, the state is immutable. In simple terms it means that you should not modify it directly. Instead a new object should be created to set the state using setState.

The splice() methods mutate an array. filter() does not mutate the array on which it is called. It is better to do the following method :

const deleted=state.products.filter((item)=>item.id !=== action.payload)

return { ...state, products: deleted}

And if you want to store something in localstorage, it is better to use the lifecycle in the react:

componentDidUpdate() for class component useEffect for functional component

about 4 years ago · Juan Pablo Isaza Relatório

0

I am guessing that, when you are clicking it on the second time it is causing problem because of the synchronous nature of localstorage .

Try this

const asyncLocalStorage = {
    setItem: function (key, value) {
        return Promise.resolve().then(function () {
            localStorage.setItem(key, value);
        });
    },
    getItem: function (key) {
        return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
    }
};
case 'REMOVE_ITEM': {
      let products = state.products
      for( var i = 0; i < products.length; i++){ 
    
        if ( products[i].id === action.payload) { 
          products.splice(i, 1); 
        }
      }

      let result = {...state, products: products, productSelected: products[0]}
      asyncLocalStorage.setItem('state', JSON.stringify(result))
      console.log(result);
      return { ...result};
    }

Reference : Link

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