Skip to content

Commit 138d347

Browse files
committed
persist cart and wishlist in localStorage
1 parent fd836cd commit 138d347

1 file changed

Lines changed: 23 additions & 11 deletions

File tree

frontend/src/App.jsx

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,12 @@ function App() {
1515
const [selectedThemes, setSelectedThemes] = useState([]);
1616
const [selectedProduct, setSelectedProduct] = useState(null);
1717
const [activeOverlay, setActiveOverlay] = useState(null);
18-
const [cartItems, setCartItems] = useState([]);
19-
const [wishlistItems, setWishlistItems] = useState([]);
18+
const [cartItems, setCartItems] = useState(() => {
19+
try { return JSON.parse(localStorage.getItem('zappify_cart')) || []; } catch { return []; }
20+
});
21+
const [wishlistItems, setWishlistItems] = useState(() => {
22+
try { return JSON.parse(localStorage.getItem('zappify_wishlist')) || []; } catch { return []; }
23+
});
2024
const [sortOption, setSortOption] = useState('recommended');
2125
const [activeNav, setActiveNav] = useState('MEN');
2226
const [sneakersView, setSneakersView] = useState(false);
@@ -78,23 +82,30 @@ function App() {
7882
const addToCart = (product, size) => {
7983
setCartItems(prev => {
8084
const exists = prev.find(i => i.id === product.id && i.size === size);
81-
if (exists) {
82-
return prev.map(i => i.id === product.id && i.size === size ? { ...i, qty: i.qty + 1 } : i);
83-
}
84-
return [...prev, { ...product, size, qty: 1 }];
85+
const updated = exists
86+
? prev.map(i => i.id === product.id && i.size === size ? { ...i, qty: i.qty + 1 } : i)
87+
: [...prev, { ...product, size, qty: 1 }];
88+
localStorage.setItem('zappify_cart', JSON.stringify(updated));
89+
return updated;
8590
});
8691
};
8792

8893
const removeFromCart = (id, size) => {
89-
setCartItems(prev => prev.filter(i => !(i.id === id && i.size === size)));
94+
setCartItems(prev => {
95+
const updated = prev.filter(i => !(i.id === id && i.size === size));
96+
localStorage.setItem('zappify_cart', JSON.stringify(updated));
97+
return updated;
98+
});
9099
};
91100

92101
const toggleWishlist = (product) => {
93-
setWishlistItems(prev =>
94-
prev.find(i => i.id === product.id)
102+
setWishlistItems(prev => {
103+
const updated = prev.find(i => i.id === product.id)
95104
? prev.filter(i => i.id !== product.id)
96-
: [...prev, product]
97-
);
105+
: [...prev, product];
106+
localStorage.setItem('zappify_wishlist', JSON.stringify(updated));
107+
return updated;
108+
});
98109
};
99110

100111
const isWishlisted = (id) => wishlistItems.some(i => i.id === id);
@@ -222,6 +233,7 @@ function App() {
222233
setPlacedOrders(updated);
223234
localStorage.setItem(getOrdersKey(loggedInUser), JSON.stringify(updated));
224235
setCartItems([]);
236+
localStorage.removeItem('zappify_cart');
225237
}}
226238
/>
227239
)}

0 commit comments

Comments
 (0)