简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM