Skip to content

Commit

Permalink
fix : context API 활용해서 장바구니 상품 수량 카운트하도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
00kang committed Jun 7, 2024
1 parent ac620bb commit a2244a1
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 20 deletions.
5 changes: 3 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import "./App.css";
import { Header } from "./components/Header/Header";
import { ProductSection } from "./components/ProductSection/ProductSection";
import { ToastNotification } from "./components/ToastNotification/ToastNotification";
import { CartProvider } from "./context/cartContext";

const App = () => {
return (
<>
<CartProvider>
<Header />
<ToastNotification />
<ProductSection />
</>
</CartProvider>
);
};

Expand Down
21 changes: 3 additions & 18 deletions src/components/Button/CartButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect, useState } from "react";
import { getCartItems } from "../../api/cart";
import { ShoppingCartIcon } from "../../assets";
import { useCart } from "../../context/cartContext";
import { BaseButton } from "./BaseButton";
import { StyledCartButtonImg, StyledCartCount, StyledContainer } from "./CartButton.styled";

Expand All @@ -9,27 +8,13 @@ interface CartButtonProps {
}

export const CartButton = ({ onClick = () => {} }: CartButtonProps) => {
const [cartCount, setCartCount] = useState<number>(0);

const fetchCartItems = async () => {
try {
const cartItems = await getCartItems();
setCartCount(cartItems.length);
} catch (error) {
console.error("Failed to fetch cart counts", error);
setCartCount(0);
}
};

useEffect(() => {
fetchCartItems();
}, []);
const { cartItems } = useCart();

return (
<BaseButton onClick={onClick}>
<StyledContainer>
<StyledCartButtonImg src={ShoppingCartIcon} alt="" />
<StyledCartCount>{cartCount}</StyledCartCount>
<StyledCartCount>{cartItems.length}</StyledCartCount>
</StyledContainer>
</BaseButton>
);
Expand Down
4 changes: 4 additions & 0 deletions src/components/ProductItem/ProductItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
StyledProductPrice,
StyledWrapper,
} from "./ProductItem.styled";
import { useCart } from "../../context/cartContext";

export const ProductItem = ({
id,
Expand All @@ -21,6 +22,7 @@ export const ProductItem = ({
const [isInCart, setIsInCart] = useState(false);
const [cartItemId, setCartItemId] = useState<number | null>(null);
const { setErrorStatus } = useError();
const { fetchCartItems } = useCart();

const fetchCartItemStatus = async () => {
try {
Expand All @@ -38,6 +40,7 @@ export const ProductItem = ({
await addCartItem(id, 1);
setIsInCart(true);
await fetchCartItemStatus();
fetchCartItems();
} catch (error) {
setErrorStatus(error.response?.status);
setIsInCart(false);
Expand All @@ -51,6 +54,7 @@ export const ProductItem = ({
await removeCartItem(cartItemId);
setIsInCart(false);
setCartItemId(null);
fetchCartItems();
} catch (error) {
setErrorStatus(error.response?.status);
setIsInCart(true);
Expand Down
43 changes: 43 additions & 0 deletions src/context/cartContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { createContext, useContext, useState, ReactNode, useEffect } from "react";
import { getCartItems } from "../api/cart";

interface CartItem {
id: number;
quantity: number;
}

interface CartContextType {
cartItems: CartItem[];
fetchCartItems: () => Promise<void>;
}

const CartContext = createContext<CartContextType | undefined>(undefined);

export const CartProvider = ({ children }: { children: ReactNode }) => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);

const fetchCartItems = async () => {
try {
const items = await getCartItems();
setCartItems(items.map((item) => ({ id: item.product.id, quantity: item.quantity })));
} catch (error) {
console.error("Failed to fetch cart items", error);
}
};

useEffect(() => {
fetchCartItems();
}, []);

return (
<CartContext.Provider value={{ cartItems, fetchCartItems }}>{children}</CartContext.Provider>
);
};

export const useCart = () => {
const context = useContext(CartContext);
if (!context) {
throw new Error("useCart must be used within a CartProvider");
}
return context;
};

0 comments on commit a2244a1

Please sign in to comment.