Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda