From ac620bbfc0b37770b01e6c0088b91803fa223b5f Mon Sep 17 00:00:00 2001 From: 00kang Date: Fri, 7 Jun 2024 17:01:34 +0900 Subject: [PATCH] =?UTF-8?q?fix=20:=20=EC=9E=A5=EB=B0=94=EA=B5=AC=EB=8B=88?= =?UTF-8?q?=20=EB=8B=B4=EA=B3=A0=20=EB=B9=BC=EB=8A=94=20=EB=B2=84=ED=8A=BC?= =?UTF-8?q?=20=EC=83=81=ED=83=9C=20=EB=B6=88=EC=95=88=EC=A0=95=ED=95=9C=20?= =?UTF-8?q?=EC=83=81=ED=83=9C=20=ED=95=B4=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 장바구니 상품 동기화 로직 순서 수정 - 버튼 동작 코드 분리 --- src/components/ProductItem/ProductItem.tsx | 50 +++++++++++++++------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/src/components/ProductItem/ProductItem.tsx b/src/components/ProductItem/ProductItem.tsx index db77d258a..4b320f17d 100644 --- a/src/components/ProductItem/ProductItem.tsx +++ b/src/components/ProductItem/ProductItem.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { addCartItem, getCartItems, removeCartItem } from "../../api/cart"; +import { useError } from "../../context/errorContext"; import { formatPrice } from "../../utils/format"; import { CartActionButton } from "../Button"; import { @@ -19,6 +20,7 @@ export const ProductItem = ({ }: Pick) => { const [isInCart, setIsInCart] = useState(false); const [cartItemId, setCartItemId] = useState(null); + const { setErrorStatus } = useError(); const fetchCartItemStatus = async () => { try { @@ -27,31 +29,47 @@ export const ProductItem = ({ setIsInCart(!!cartItem); setCartItemId(cartItem ? cartItem.id : null); } catch (error) { - console.error("Failed to fetch cart item status", error); + setErrorStatus(error.response?.status); } }; - useEffect(() => { - fetchCartItemStatus(); - }, [id]); + const handleAddToCart = async () => { + try { + await addCartItem(id, 1); + setIsInCart(true); + await fetchCartItemStatus(); + } catch (error) { + setErrorStatus(error.response?.status); + setIsInCart(false); + } + }; + + const handleRemoveFromCart = async () => { + if (cartItemId === null) return; - const handleButtonClick = async () => { try { - if (isInCart) { - if (cartItemId !== null) { - await removeCartItem(cartItemId); - setIsInCart(false); - setCartItemId(null); - } - } else { - await addCartItem(id, 1); - await fetchCartItemStatus(); - } + await removeCartItem(cartItemId); + setIsInCart(false); + setCartItemId(null); } catch (error) { - console.error("Error handling cart action:", error); + setErrorStatus(error.response?.status); + setIsInCart(true); + setCartItemId(cartItemId); } }; + const handleButtonClick = async () => { + if (isInCart) { + await handleRemoveFromCart(); + } else { + await handleAddToCart(); + } + }; + + useEffect(() => { + fetchCartItemStatus(); + }, [id]); + return (