Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantly update state when any changes into the localStorage in React.js

How to update cart page data instantly when any changes in the localStorage myCart array? Here is my code below

const [cart, setCart] = React.useState([])

React.useEffect(() => {
    setCart(JSON.parse(localStorage.getItem('myCart')) || [])
}, [])

the cart is updated when the page reloads but not when new item adds or updates any existing items!

How can I achieve that, which is cart update instantly if any changes into 'localStorage`?

Thanks in advance.

like image 946
jesica Avatar asked Jan 25 '23 21:01

jesica


1 Answers

You can add an eventlistener to the localstorage event

React.useEffect(() => {
    
window.addEventListener('storage', () => {
  // When local storage changes, dump the list to
  // the console.
   setCart(JSON.parse(localStorage.getItem('myCart')) || [])   
});

   
}, [])

The storage event of the Window interface fires when a storage area (localStorage) has been modified.The storage event is only triggered when a window other than itself makes the changes.

.

like image 106
Shubh Avatar answered Feb 14 '23 11:02

Shubh