Skip to content

Commit

Permalink
fix : 장바구니 담고 빼는 버튼 상태 불안정한 상태 해결
Browse files Browse the repository at this point in the history
- 장바구니 상품 동기화 로직 순서 수정
- 버튼 동작 코드 분리
  • Loading branch information
00kang committed Jun 7, 2024
1 parent 3f672d7 commit ac620bb
Showing 1 changed file with 34 additions and 16 deletions.
50 changes: 34 additions & 16 deletions src/components/ProductItem/ProductItem.tsx
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -19,6 +20,7 @@ export const ProductItem = ({
}: Pick<ProductProps, "id" | "imageUrl" | "name" | "price">) => {
const [isInCart, setIsInCart] = useState(false);
const [cartItemId, setCartItemId] = useState<number | null>(null);
const { setErrorStatus } = useError();

const fetchCartItemStatus = async () => {
try {
Expand All @@ -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);

This comment has been minimized.

Copy link
@365kim

365kim Jun 7, 2024

👍

}
};

useEffect(() => {
fetchCartItemStatus();
}, [id]);
const handleAddToCart = async () => {
try {
await addCartItem(id, 1);
setIsInCart(true);
await fetchCartItemStatus();

This comment has been minimized.

Copy link
@365kim

365kim Jun 7, 2024

오 여기서 await addCartItem() 요청은 성공하고 await fetchCartItemStatus()에서만 error가 발생한 경우에도 setIsInCart(false)를 실행하게 되는걸까요?

} 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 (
<StyledProductItem>
<StyledProductImg src={imageUrl} alt="" />
Expand Down

0 comments on commit ac620bb

Please sign in to comment.