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

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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