Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!