cart checker for remove cart when slug changed

This commit is contained in:
hamid zarghami
2025-12-29 09:04:58 +03:30
parent d6c2f2630d
commit 98b834b982
5 changed files with 65 additions and 7 deletions
+23 -4
View File
@@ -1,4 +1,5 @@
import { useMemo } from "react";
import { useCallback, useMemo } from "react";
import { useParams } from "next/navigation";
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { useReceiptStore } from "@/zustand/receiptStore";
import {
@@ -10,7 +11,9 @@ import {
export const useCart = () => {
const { isSuccess } = useGetProfile();
const { clear, increment, decrement, items } = useReceiptStore();
const params = useParams();
const currentSlug = (params.name as string) || null;
const { clear, increment, decrement, items, slug, setSlug } = useReceiptStore();
const { mutate: mutateIncrementCart } = useIncrementCart();
const { mutate: mutateDecrementCart } = useDecrementCart();
const { mutate: mutateClearCart } = useClearCart();
@@ -20,6 +23,10 @@ export const useCart = () => {
if (isSuccess) {
mutateIncrementCart(id);
} else {
// تنظیم slug هنگام افزودن آیتم به سبد (فقط برای کاربران لاگین نشده)
if (currentSlug && slug !== currentSlug) {
setSlug(currentSlug);
}
increment(id);
}
};
@@ -32,13 +39,13 @@ export const useCart = () => {
}
};
const clearCart = () => {
const clearCart = useCallback(() => {
if (isSuccess) {
mutateClearCart();
} else {
clear();
}
};
}, [isSuccess, mutateClearCart, clear]);
const cartItemsMap = useMemo(() => {
if (isSuccess) {
@@ -58,8 +65,20 @@ export const useCart = () => {
return false;
};
// برای کاربران لاگین شده، slug از API می‌آید (در cartItems.data.restaurantId)
// برای کاربران لاگین نشده، slug از receiptStore می‌آید
const cartSlug = useMemo(() => {
if (isSuccess && cartItems?.data?.restaurantId) {
// اگر از API آمده، می‌توانیم restaurantId را برگردانیم
// اما بهتر است slug را از URL بگیریم چون API ممکن است restaurantId را برگرداند نه slug
return currentSlug;
}
return slug;
}, [isSuccess, cartItems?.data?.restaurantId, currentSlug, slug]);
return {
items: cartItemsMap,
slug: cartSlug,
increment,
decrement,
clear,
+5 -1
View File
@@ -3,6 +3,7 @@ import React from 'react'
import type { Metadata, Viewport } from 'next'
import { getRestaurant } from './lib/getRestaurant'
import { notFound } from 'next/navigation'
import CartChecker from '@/components/CartChecker'
export const dynamic = 'force-dynamic'
export const revalidate = 0
@@ -85,7 +86,10 @@ export default async function Layout({
try {
const { name } = await params
await getRestaurant(name)
return <PreferenceWrapper>{children}</PreferenceWrapper>
return <>
<PreferenceWrapper>{children}</PreferenceWrapper>
<CartChecker />
</>
} catch (error) {
if (error instanceof Error && error.message === 'RESTAURANT_NOT_FOUND') {
notFound()