changed order
This commit is contained in:
@@ -22,19 +22,13 @@ import ImageCarousel from "./imageCarousel/index";
|
||||
|
||||
// Helper function to strip HTML tags and truncate text
|
||||
const truncateDescription = (htmlString, maxLength = 80) => {
|
||||
// Create a temporary div to parse HTML
|
||||
const tempDiv = document.createElement("div");
|
||||
tempDiv.innerHTML = htmlString;
|
||||
|
||||
// Get text content without HTML tags
|
||||
const textContent = tempDiv.textContent || tempDiv.innerText || "";
|
||||
|
||||
// Truncate the text
|
||||
const truncatedText =
|
||||
textContent.length > maxLength
|
||||
? textContent.substring(0, maxLength).trim() + "..."
|
||||
: textContent;
|
||||
|
||||
return truncatedText;
|
||||
};
|
||||
|
||||
@@ -45,51 +39,70 @@ const ProductCard = ({
|
||||
onAddToCart,
|
||||
onToggleFavorite,
|
||||
isFavorite = false,
|
||||
descriptionMaxLength = 85, // New prop to control description length
|
||||
descriptionMaxLength = 85,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [stockErrorModalVisible, setStockErrorModalVisible] = useState(false);
|
||||
const [addFavorite] = useAddFavoriteMutation();
|
||||
const [removeFavorite] = useRemoveFavoriteMutation();
|
||||
const { data: favoriteProducts = [], refetch } = useGetFavoritesQuery();
|
||||
const { data: favoriteProducts = [] } = useGetFavoritesQuery();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [localIsFavorite, setLocalIsFavorite] = useState(
|
||||
favoriteProducts.some((fav) => fav.product?.id === product.id)
|
||||
);
|
||||
// Process description
|
||||
|
||||
const truncatedDesc = truncateDescription(
|
||||
product.description,
|
||||
descriptionMaxLength
|
||||
);
|
||||
|
||||
// ✅ Sadece cache'den oku, yeni request gönderme
|
||||
const { data: cartData } = useGetCartQuery(undefined, {
|
||||
selectFromResult: (result) => ({
|
||||
data: result.data,
|
||||
}),
|
||||
refetchOnMountOrArgChange: false, // ✅ Mount'ta yeniden çağırma
|
||||
refetchOnFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
|
||||
const [addToCart] = useAddToCartMutation();
|
||||
const [updateCartItem] = useUpdateCartItemMutation();
|
||||
const [removeFromCart] = useRemoveFromCartMutation();
|
||||
|
||||
const cartItem = cartData?.data?.find(
|
||||
(item) => item.product?.id === product.id || item.product_id === product.id
|
||||
);
|
||||
const quantity = cartItem?.quantity || cartItem?.product_quantity || 0;
|
||||
const [localQuantity, setLocalQuantity] = useState(0);
|
||||
const [pendingQuantity, setPendingQuantity] = useState(localQuantity);
|
||||
// ✅ Cart data'yı düzgün parse et
|
||||
const getCartItem = () => {
|
||||
if (!cartData || typeof cartData !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Eğer data grouped object ise (store bazlı)
|
||||
const allCartItems = Object.values(cartData).flat();
|
||||
|
||||
return allCartItems.find(
|
||||
(item) =>
|
||||
item.product?.id === product.id || item.product_id === product.id
|
||||
);
|
||||
};
|
||||
|
||||
const cartItem = getCartItem();
|
||||
const [localQuantity, setLocalQuantity] = useState(0);
|
||||
const [pendingQuantity, setPendingQuantity] = useState(0);
|
||||
|
||||
// ✅ Cart item değiştiğinde local state'i güncelle
|
||||
useEffect(() => {
|
||||
if (cartItem) {
|
||||
setLocalQuantity(cartItem.quantity || cartItem.product_quantity || 0);
|
||||
setPendingQuantity(cartItem.quantity || cartItem.product_quantity || 0);
|
||||
const qty = cartItem.quantity || cartItem.product_quantity || 0;
|
||||
setLocalQuantity(qty);
|
||||
setPendingQuantity(qty);
|
||||
} else {
|
||||
setLocalQuantity(0);
|
||||
setPendingQuantity(0);
|
||||
}
|
||||
}, [cartData, cartItem]);
|
||||
}, [cartItem]); // ✅ Sadece cartItem değişince, cartData değil
|
||||
|
||||
// ✅ Favorite state'i güncelle
|
||||
useEffect(() => {
|
||||
if (Array.isArray(favoriteProducts)) {
|
||||
const isFav = favoriteProducts.some(
|
||||
@@ -102,34 +115,46 @@ const ProductCard = ({
|
||||
const handleAddToCart = async (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (product.stock <= 0) {
|
||||
setStockErrorModalVisible(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// ✅ Optimistic update
|
||||
setLocalQuantity((prev) => prev + 1);
|
||||
setPendingQuantity((prev) => prev + 1);
|
||||
|
||||
try {
|
||||
await addToCart({ productId: product.id, quantity: 1 }).unwrap();
|
||||
// ✅ Başarılı - RTK Query otomatik cache'i güncelleyecek
|
||||
} catch (error) {
|
||||
console.error("Failed to add to cart:", error);
|
||||
// ✅ Hata varsa geri al
|
||||
setLocalQuantity((prev) => prev - 1);
|
||||
setPendingQuantity((prev) => prev - 1);
|
||||
}
|
||||
};
|
||||
|
||||
// ✅ Debounced update - sadece mutation, refetch yok
|
||||
useEffect(() => {
|
||||
const updateCart = async () => {
|
||||
if (pendingQuantity !== quantity && pendingQuantity > 0) {
|
||||
const currentCartQty =
|
||||
cartItem?.quantity || cartItem?.product_quantity || 0;
|
||||
|
||||
if (pendingQuantity !== currentCartQty && pendingQuantity > 0) {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await updateCartItem({
|
||||
productId: product.id,
|
||||
quantity: pendingQuantity,
|
||||
}).unwrap();
|
||||
// ✅ RTK Query invalidatesTags ile otomatik güncellenecek
|
||||
} catch (error) {
|
||||
console.error("Failed to update cart item:", error);
|
||||
setLocalQuantity(quantity);
|
||||
setPendingQuantity(quantity);
|
||||
// ✅ Hata varsa önceki değere dön
|
||||
setLocalQuantity(currentCartQty);
|
||||
setPendingQuantity(currentCartQty);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -138,12 +163,14 @@ const ProductCard = ({
|
||||
|
||||
const debouncedUpdate = debounce(updateCart, 300);
|
||||
|
||||
if (pendingQuantity !== quantity) {
|
||||
const currentCartQty =
|
||||
cartItem?.quantity || cartItem?.product_quantity || 0;
|
||||
if (pendingQuantity !== currentCartQty) {
|
||||
debouncedUpdate();
|
||||
}
|
||||
|
||||
return () => debouncedUpdate.cancel();
|
||||
}, [pendingQuantity, quantity, product.id, updateCartItem]);
|
||||
}, [pendingQuantity, cartItem, product.id, updateCartItem]);
|
||||
|
||||
const handleQuantityIncrease = (event) => {
|
||||
event.preventDefault();
|
||||
@@ -167,12 +194,18 @@ const ProductCard = ({
|
||||
if (isLoading) return;
|
||||
|
||||
if (pendingQuantity <= 1) {
|
||||
// ✅ Sıfıra düşünce direkt sil
|
||||
setPendingQuantity(0);
|
||||
setLocalQuantity(0);
|
||||
setIsLoading(true);
|
||||
|
||||
removeFromCart({ productId: product.id })
|
||||
.unwrap()
|
||||
.then(() => {
|
||||
// ✅ Başarılı - RTK Query cache'i güncelleyecek
|
||||
})
|
||||
.catch(() => {
|
||||
// ✅ Hata varsa geri al
|
||||
setLocalQuantity(1);
|
||||
setPendingQuantity(1);
|
||||
})
|
||||
@@ -188,24 +221,26 @@ const ProductCard = ({
|
||||
const handleToggleFavorite = async (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (isLoading) return;
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
// ✅ Optimistic update
|
||||
setLocalIsFavorite(!localIsFavorite);
|
||||
|
||||
try {
|
||||
if (localIsFavorite) {
|
||||
const result = await removeFavorite(product.id).unwrap();
|
||||
if (result === "Removed" || result?.status === "success") {
|
||||
setLocalIsFavorite(false);
|
||||
}
|
||||
// ✅ Başarılı - RTK Query otomatik güncelleyecek
|
||||
} else {
|
||||
const result = await addFavorite(product.id).unwrap();
|
||||
if (result === "Added" || result?.status === "success") {
|
||||
setLocalIsFavorite(true);
|
||||
}
|
||||
// ✅ Başarılı - RTK Query otomatik güncelleyecek
|
||||
}
|
||||
await refetch();
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle favorite:", error);
|
||||
// ✅ Hata varsa geri al
|
||||
setLocalIsFavorite(localIsFavorite);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -234,8 +269,6 @@ const ProductCard = ({
|
||||
</div>
|
||||
<div className={styles.productInfo}>
|
||||
<h3 className={styles.productName}>{name}</h3>
|
||||
|
||||
{/* Simple truncated description */}
|
||||
<p className={styles.productDescription}>{truncatedDesc}</p>
|
||||
|
||||
<div className={styles.priceContainer}>
|
||||
@@ -252,6 +285,7 @@ const ProductCard = ({
|
||||
<button
|
||||
className={styles.favoriteButton}
|
||||
onClick={handleToggleFavorite}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{localIsFavorite ? <IoMdHeart /> : <IoMdHeartEmpty />}
|
||||
</button>
|
||||
@@ -263,6 +297,7 @@ const ProductCard = ({
|
||||
<button
|
||||
onClick={handleQuantityDecrease}
|
||||
className={styles.quantityBtn}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<DecreaseIcon />
|
||||
</button>
|
||||
@@ -270,6 +305,7 @@ const ProductCard = ({
|
||||
<button
|
||||
onClick={handleQuantityIncrease}
|
||||
className={styles.quantityBtn}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<IncreaseIcon />
|
||||
</button>
|
||||
@@ -278,6 +314,7 @@ const ProductCard = ({
|
||||
<button
|
||||
className={styles.addToCartButton}
|
||||
onClick={handleAddToCart}
|
||||
disabled={isLoading || product.stock === 0}
|
||||
>
|
||||
<FaShoppingCart />
|
||||
</button>
|
||||
@@ -287,7 +324,6 @@ const ProductCard = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stock Error Modal */}
|
||||
<Modal
|
||||
title={t("common.warning")}
|
||||
open={stockErrorModalVisible}
|
||||
|
||||
Reference in New Issue
Block a user