diff --git a/src/components/shop/CartDrawer.jsx b/src/components/shop/CartDrawer.jsx index 7b2d8707..f4444008 100644 --- a/src/components/shop/CartDrawer.jsx +++ b/src/components/shop/CartDrawer.jsx @@ -65,6 +65,8 @@ function CartDrawer({ open, setOpen }) { const handleDeleteSwag = (cartItemId) => { removeSwagFromCart(cartItemId); deleteFromLocalStorage(cartItemId); + // dispatch custom event to notify cart change + window.dispatchEvent(new Event("swagListUpdated")); }; const handleCheckout = () => { diff --git a/src/components/shop/CartIcon.jsx b/src/components/shop/CartIcon.jsx index c9b5faf7..439a0027 100644 --- a/src/components/shop/CartIcon.jsx +++ b/src/components/shop/CartIcon.jsx @@ -1,7 +1,33 @@ +import { useEffect, useState } from "react"; import { MdAddShoppingCart } from "react-icons/md"; import SectionWrapper from "./SectionWrapper"; function CartIcon() { + const [cartProducts, setCartProducts] = useState(() => { + // Initialize state with the value from localStorage if it exists + const storedProducts = localStorage.getItem("swagList"); + return storedProducts ? JSON.parse(storedProducts) : []; + }); + + useEffect(() => { + // Event listener for storage changes in other tabs/windows + const handleStorageChange = (e) => { + const storedProducts = localStorage.getItem("swagList"); + setCartProducts(storedProducts ? JSON.parse(storedProducts) : []); + }; + + // Listen for "storage" events, whenever swagList is updated from another tab + window.addEventListener("storage", handleStorageChange); + // Listen for custom swagListUpdated events, fired whenever swagList is updated + window.addEventListener("swagListUpdated", handleStorageChange); + + // Cleanup event listeners on unmount + return () => { + window.removeEventListener("storage", handleStorageChange); + window.removeEventListener("swagListUpdated", handleStorageChange); + }; + }, []); + return (
@@ -10,7 +36,7 @@ function CartIcon() {
-

1

+

{cartProducts?.length}

diff --git a/src/pages/shop/SingleItemPage.jsx b/src/pages/shop/SingleItemPage.jsx index 47eb5f57..e0cf2c7f 100644 --- a/src/pages/shop/SingleItemPage.jsx +++ b/src/pages/shop/SingleItemPage.jsx @@ -128,6 +128,8 @@ export default function SingleItemPage() { }); // Add to local storage addToLocalStorage(); + // dispatch custom event to notify cart change + window.dispatchEvent(new Event("swagListUpdated")); // open cart setOpen(true);