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.
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.
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With