online cart with Optimistic state

This commit is contained in:
hamid zarghami
2025-12-01 15:01:18 +03:30
parent dd18870b85
commit bf043512e9
4 changed files with 125 additions and 73 deletions
+5 -42
View File
@@ -1,4 +1,3 @@
import { useState } from "react";
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
import { useReceiptStore } from "@/zustand/receiptStore";
import {
@@ -11,33 +10,14 @@ import {
export const useCart = () => {
const { isSuccess } = useGetProfile();
const { clear, increment, decrement, items } = useReceiptStore();
const [loadingItems, setLoadingItems] = useState<Set<string | number>>(
new Set()
);
const { mutate: mutateIncrementCart } = useIncrementCart();
const { mutate: mutateDecrementCart } = useDecrementCart();
const { mutate: mutateClearCart } = useClearCart();
const { data: cartItems } = useGetCartItems();
const { data: cartItems } = useGetCartItems(isSuccess);
const addToCart = (id: string | number) => {
if (isSuccess) {
setLoadingItems((prev) => new Set(prev).add(id));
mutateIncrementCart(id, {
onSuccess: () => {
setLoadingItems((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
},
onError: () => {
setLoadingItems((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
},
});
mutateIncrementCart(id);
} else {
increment(id);
}
@@ -45,23 +25,7 @@ export const useCart = () => {
const removeFromCart = (id: string | number) => {
if (isSuccess) {
setLoadingItems((prev) => new Set(prev).add(id));
mutateDecrementCart(id, {
onSuccess: () => {
setLoadingItems((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
},
onError: () => {
setLoadingItems((prev) => {
const next = new Set(prev);
next.delete(id);
return next;
});
},
});
mutateDecrementCart(id);
} else {
decrement(id);
}
@@ -89,9 +53,8 @@ export const useCart = () => {
}
};
const isItemLoading = (id: string | number) => {
if (!isSuccess) return false;
return loadingItems.has(id);
const isItemLoading = () => {
return false;
};
return {
@@ -1,5 +1,6 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import * as api from "../service/CartService";
import type { CartResponse } from "../types/Types";
export const useBulkCart = () => {
const queryClient = useQueryClient();
@@ -15,7 +16,48 @@ export const useIncrementCart = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.increment,
onSuccess: () => {
onMutate: async (id: string | number) => {
await queryClient.cancelQueries({ queryKey: ["cart-items"] });
const previousCart = queryClient.getQueryData<CartResponse>([
"cart-items",
]);
if (previousCart?.data) {
const existingItem = previousCart.data.items.find(
(item) => item.foodId === String(id)
);
if (existingItem) {
const updatedItems = previousCart.data.items.map((item) => {
if (item.foodId === String(id)) {
return {
...item,
quantity: item.quantity + 1,
};
}
return item;
});
queryClient.setQueryData<CartResponse>(["cart-items"], {
...previousCart,
data: {
...previousCart.data,
items: updatedItems,
totalItems: previousCart.data.totalItems + 1,
},
});
}
}
return { previousCart };
},
onError: (_err, _id, context) => {
if (context?.previousCart) {
queryClient.setQueryData(["cart-items"], context.previousCart);
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
},
});
@@ -25,7 +67,48 @@ export const useDecrementCart = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.decrement,
onSuccess: () => {
onMutate: async (id: string | number) => {
await queryClient.cancelQueries({ queryKey: ["cart-items"] });
const previousCart = queryClient.getQueryData<CartResponse>([
"cart-items",
]);
if (previousCart?.data) {
const updatedItems = previousCart.data.items
.map((item) => {
if (item.foodId === String(id)) {
const newQuantity = item.quantity - 1;
if (newQuantity <= 0) {
return null;
}
return {
...item,
quantity: newQuantity,
};
}
return item;
})
.filter((item): item is NonNullable<typeof item> => item !== null);
queryClient.setQueryData<CartResponse>(["cart-items"], {
...previousCart,
data: {
...previousCart.data,
items: updatedItems,
totalItems: Math.max(0, previousCart.data.totalItems - 1),
},
});
}
return { previousCart };
},
onError: (_err, _id, context) => {
if (context?.previousCart) {
queryClient.setQueryData(["cart-items"], context.previousCart);
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
},
});
@@ -35,15 +118,43 @@ export const useClearCart = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: api.clear,
onSuccess: () => {
onMutate: async () => {
await queryClient.cancelQueries({ queryKey: ["cart-items"] });
const previousCart = queryClient.getQueryData<CartResponse>([
"cart-items",
]);
if (previousCart?.data) {
queryClient.setQueryData<CartResponse>(["cart-items"], {
...previousCart,
data: {
...previousCart.data,
items: [],
totalItems: 0,
subTotal: 0,
total: 0,
},
});
}
return { previousCart };
},
onError: (_err, _variables, context) => {
if (context?.previousCart) {
queryClient.setQueryData(["cart-items"], context.previousCart);
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
},
});
};
export const useGetCartItems = () => {
export const useGetCartItems = (enabled = true) => {
return useQuery({
queryKey: ["cart-items"],
queryFn: api.getCartItems,
enabled,
});
};