Home > other >  How to getItem every time, value is changed/updated. localStorage, JS
How to getItem every time, value is changed/updated. localStorage, JS

Time:02-19

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.

CodePudding user response:

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.

CodePudding user response:

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)
};
  • Related