Skip to content

Commit

Permalink
feat: display and keep track of cart items count in the cart icon
Browse files Browse the repository at this point in the history
  • Loading branch information
alvyynm committed Oct 29, 2024
1 parent 34a1fac commit e3e6787
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/components/shop/CartDrawer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 = () => {
Expand Down
28 changes: 27 additions & 1 deletion src/components/shop/CartIcon.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<SectionWrapper>
<div className="flex justify-end relative">
Expand All @@ -10,7 +36,7 @@ function CartIcon() {
<MdAddShoppingCart color="white" className="h-full w-full" />
</div>
<div className="absolute bottom-0 right-0 bg-[#B3261E] text-white text-xs font-medium rounded-full w-5 h-5 flex items-center justify-center">
<p>1</p>
<p>{cartProducts?.length}</p>
</div>
</div>
</div>
Expand Down
2 changes: 2 additions & 0 deletions src/pages/shop/SingleItemPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit e3e6787

Please sign in to comment.