show variant in carts

This commit is contained in:
hamid zarghami
2026-02-15 10:39:31 +03:30
parent a25086bb8c
commit 44fb0be875
6 changed files with 73 additions and 22 deletions
+39 -8
View File
@@ -8,20 +8,39 @@ import {
useGetCartItems,
useIncrementCart,
} from "../hooks/useCartData";
import { toast } from "@/components/Toast";
import { extractErrorMessage } from "@/lib/func";
export const useCart = () => {
const { isSuccess } = useGetProfile();
const params = useParams();
const currentSlug = (params.name as string) || null;
const { clear, increment, decrement, items, slug, setSlug } = useReceiptStore();
const { mutate: mutateIncrementCart, isPending: isIncrementPending } = useIncrementCart();
const { mutate: mutateDecrementCart, isPending: isDecrementPending } = useDecrementCart();
const {
clear,
increment,
decrement,
items,
slug,
setSlug,
} = useReceiptStore();
const {
mutate: mutateIncrementCart,
isPending: isIncrementPending,
} = useIncrementCart();
const {
mutate: mutateDecrementCart,
isPending: isDecrementPending,
} = useDecrementCart();
const { mutate: mutateClearCart } = useClearCart();
const { data: cartItems } = useGetCartItems(isSuccess);
const addToCart = (id: string | number) => {
if (isSuccess) {
mutateIncrementCart(id);
mutateIncrementCart(id, {
onError: (error) => {
toast(extractErrorMessage(error), "error");
},
});
} else {
// تنظیم slug هنگام افزودن آیتم به سبد (فقط برای کاربران لاگین نشده)
if (currentSlug && slug !== currentSlug) {
@@ -33,7 +52,11 @@ export const useCart = () => {
const removeFromCart = (id: string | number) => {
if (isSuccess) {
mutateDecrementCart(id);
mutateDecrementCart(id, {
onError: (error) => {
toast(extractErrorMessage(error), "error");
},
});
} else {
decrement(id);
}
@@ -41,7 +64,11 @@ export const useCart = () => {
const clearCart = useCallback(() => {
if (isSuccess) {
mutateClearCart();
mutateClearCart(undefined, {
onError: (error) => {
toast(extractErrorMessage(error), "error");
},
});
} else {
clear();
}
@@ -53,9 +80,13 @@ export const useCart = () => {
return {};
}
return cartItems.data.items.reduce((acc, item) => {
acc[item.variantId] = { quantity: item.quantity };
acc[item.variantId] = {
quantity: item.quantity,
...(item.variantValue != null && { variantValue: item.variantValue }),
...(item.image != null && { image: item.image }),
};
return acc;
}, {} as Record<string | number, { quantity: number }>);
}, {} as Record<string | number, { quantity: number; variantValue?: string; image?: string }>);
} else {
return items;
}