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

209
Vistas
How to getItem every time, value is changed/updated. localStorage, JS

I have a shopping cart where i add and remove items, and i keep data in the localStorage.

I add my items like this:

const addItemToCart = (item: Object) => {
    if (typeof window === 'undefined') return;

    let myCart = JSON.parse(localStorage.getItem('myCart') || '[]');
    myCart.push(item);
    localStorage.setItem('myCart', JSON.stringify(myCart));
  };

The shopping cart is different component and i need to call in that single component getItem() every time i add item to cart.

Is there a way to watch attribute in localStorage? Because only way i see is to create some context.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can create custom event with listeners to effect on state change.

After adding/removing items (setItem), you can fire custom event:

...
// As you update localStorage, update the state as well
localStorage.setItem('myCart', JSON.stringify(myCart));

// fired custom event on localStorage data changed
const event = new CustomEvent('localdatachanged');
document.dispatchEvent(event);

// Update the state with the array
...

and add event listener in place you want:

document.addEventListener('localdatachanged', () => {
  // handler
});

In this case you can fire custom event in different places, but handle changes only in one place.

about 4 years ago · Juan Pablo Isaza Denunciar

0

localStorage does not have any state, so you have to create your own variable with state so that each time you update the localStorage, you also update the state variable:

const [cart, setCart] = useState([])
const addItemToCart = (item: Object) => {
    if (typeof window === 'undefined') return;

    let myCart = JSON.parse(localStorage.getItem('myCart') || '[]');
    myCart.push(item);
    // As you update localStorage, update the state as well
    localStorage.setItem('myCart', JSON.stringify(myCart));
    // Update the state with the array
    setCart(myCart)
};
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