-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathProductCart.tsx
More file actions
52 lines (45 loc) · 1.65 KB
/
Copy pathProductCart.tsx
File metadata and controls
52 lines (45 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// ProductCartPage.tsx
import { useEffect, useState } from "react";
import ProductList from "./ProductList";
import { ProductItem } from "@/types/Product";
import CartList from "./CartList";
export default function ProductCart({ items }: { items: ProductItem[] }) {
const [cart, setCart] = useState<{ [id: string]: number }>({}); // {"88159814281" : 1}
const [showCart, setShowCart] = useState(false); // 과제 2.1
// 카트에 담기
useEffect(() => {
const hasItems = Object.keys(cart).length > 0;
setShowCart(hasItems);
}, [cart]);
const handleAddToCart = (item: ProductItem, quantity: number) => {
setCart((prev) => ({
...prev,
[item.productId]: quantity,
}));
localStorage.setItem(item.productId, quantity + "");
localStorage.getItem(item.productId);
};
/* 과제 2-3: Cart 아이템 지우기 */
const handleRemoveFromCart = (productId: string) => {
setCart((prev) => {
const cartEntries = Object.entries(prev);
const filteredEntries = cartEntries.filter(
([key, value]) => key !== productId
);
const newCart = Object.fromEntries(filteredEntries);
return newCart;
});
localStorage.removeItem(productId);
};
return (
<div className="p-10">
{/* 상품 리스트 */}
<ProductList items={items} onAddToCart={handleAddToCart} />
{/* 장바구니 */}
{/* 2.1. 조건부 카트 보이기: 카트에 담긴 상품이 없으면 카트가 보이지 않고, 카트에 담긴 물건이 있으면 카트가 보인다 */}
{showCart && (
<CartList cart={cart} products={items} onRemove={handleRemoveFromCart} />
)}
</div>
);
}