online cart with Optimistic state
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
@@ -1,4 +1,3 @@
|
|||||||
import { useState } from "react";
|
|
||||||
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
||||||
import { useReceiptStore } from "@/zustand/receiptStore";
|
import { useReceiptStore } from "@/zustand/receiptStore";
|
||||||
import {
|
import {
|
||||||
@@ -11,33 +10,14 @@ import {
|
|||||||
export const useCart = () => {
|
export const useCart = () => {
|
||||||
const { isSuccess } = useGetProfile();
|
const { isSuccess } = useGetProfile();
|
||||||
const { clear, increment, decrement, items } = useReceiptStore();
|
const { clear, increment, decrement, items } = useReceiptStore();
|
||||||
const [loadingItems, setLoadingItems] = useState<Set<string | number>>(
|
|
||||||
new Set()
|
|
||||||
);
|
|
||||||
const { mutate: mutateIncrementCart } = useIncrementCart();
|
const { mutate: mutateIncrementCart } = useIncrementCart();
|
||||||
const { mutate: mutateDecrementCart } = useDecrementCart();
|
const { mutate: mutateDecrementCart } = useDecrementCart();
|
||||||
const { mutate: mutateClearCart } = useClearCart();
|
const { mutate: mutateClearCart } = useClearCart();
|
||||||
const { data: cartItems } = useGetCartItems();
|
const { data: cartItems } = useGetCartItems(isSuccess);
|
||||||
|
|
||||||
const addToCart = (id: string | number) => {
|
const addToCart = (id: string | number) => {
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
setLoadingItems((prev) => new Set(prev).add(id));
|
mutateIncrementCart(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;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
increment(id);
|
increment(id);
|
||||||
}
|
}
|
||||||
@@ -45,23 +25,7 @@ export const useCart = () => {
|
|||||||
|
|
||||||
const removeFromCart = (id: string | number) => {
|
const removeFromCart = (id: string | number) => {
|
||||||
if (isSuccess) {
|
if (isSuccess) {
|
||||||
setLoadingItems((prev) => new Set(prev).add(id));
|
mutateDecrementCart(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;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
decrement(id);
|
decrement(id);
|
||||||
}
|
}
|
||||||
@@ -89,9 +53,8 @@ export const useCart = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const isItemLoading = (id: string | number) => {
|
const isItemLoading = () => {
|
||||||
if (!isSuccess) return false;
|
return false;
|
||||||
return loadingItems.has(id);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import * as api from "../service/CartService";
|
import * as api from "../service/CartService";
|
||||||
|
import type { CartResponse } from "../types/Types";
|
||||||
|
|
||||||
export const useBulkCart = () => {
|
export const useBulkCart = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -15,7 +16,48 @@ export const useIncrementCart = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.increment,
|
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"] });
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -25,7 +67,48 @@ export const useDecrementCart = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.decrement,
|
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"] });
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -35,15 +118,43 @@ export const useClearCart = () => {
|
|||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: api.clear,
|
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"] });
|
queryClient.invalidateQueries({ queryKey: ["cart-items"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const useGetCartItems = () => {
|
export const useGetCartItems = (enabled = true) => {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ["cart-items"],
|
queryKey: ["cart-items"],
|
||||||
queryFn: api.getCartItems,
|
queryFn: api.getCartItems,
|
||||||
|
enabled,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -7,17 +7,13 @@ import MinusIcon from "@/components/icons/MinusIcon";
|
|||||||
import { useCart } from "@/app/[name]/(Dialogs)/cart/hook/useCart";
|
import { useCart } from "@/app/[name]/(Dialogs)/cart/hook/useCart";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import type { Food } from "@/app/[name]/(Main)/types/Types";
|
import type { Food } from "@/app/[name]/(Main)/types/Types";
|
||||||
import { Refresh } from "iconsax-react";
|
|
||||||
import { useGetProfile } from "@/app/[name]/(Profile)/profile/hooks/userProfileData";
|
|
||||||
|
|
||||||
interface MenuItemProps {
|
interface MenuItemProps {
|
||||||
food: Food;
|
food: Food;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MenuItem = ({ food }: MenuItemProps) => {
|
const MenuItem = ({ food }: MenuItemProps) => {
|
||||||
const { isSuccess } = useGetProfile();
|
const { items, addToCart, removeFromCart } = useCart();
|
||||||
const { items, addToCart, removeFromCart, isItemLoading } = useCart();
|
|
||||||
const isLoading = isItemLoading(food.id);
|
|
||||||
|
|
||||||
const quantity = useMemo(() => {
|
const quantity = useMemo(() => {
|
||||||
const item = items?.[food.id];
|
const item = items?.[food.id];
|
||||||
@@ -89,26 +85,10 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
whileTap={{ scale: 1.05 }}
|
whileTap={{ scale: 1.05 }}
|
||||||
className="bg-background active:drop-shadow-xs max-w-[115px] rounded-md w-full h-8 inline-flex p-1 justify-between items-center gap-2 relative overflow-hidden"
|
className="bg-background active:drop-shadow-xs max-w-[115px] rounded-md w-full h-8 inline-flex p-1 justify-between items-center gap-2 relative overflow-hidden"
|
||||||
>
|
>
|
||||||
{isSuccess && isLoading && (
|
|
||||||
<motion.div
|
|
||||||
className="absolute inset-0 bg-background/80 flex items-center justify-center z-10"
|
|
||||||
initial={{ opacity: 0 }}
|
|
||||||
animate={{ opacity: 1 }}
|
|
||||||
exit={{ opacity: 0 }}
|
|
||||||
>
|
|
||||||
<motion.div
|
|
||||||
animate={{ rotateZ: [0, 360] }}
|
|
||||||
transition={{ duration: 1.2, repeat: Infinity, ease: 'linear' }}
|
|
||||||
>
|
|
||||||
<Refresh className="text-foreground" size={20} />
|
|
||||||
</motion.div>
|
|
||||||
</motion.div>
|
|
||||||
)}
|
|
||||||
{quantity <= 0 ? (
|
{quantity <= 0 ? (
|
||||||
<button
|
<button
|
||||||
onClick={handleAddToCart}
|
onClick={handleAddToCart}
|
||||||
disabled={isSuccess && isLoading}
|
className="inline-flex w-full justify-center items-center gap-2"
|
||||||
className="inline-flex w-full justify-center items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
>
|
||||||
<PlusIcon />
|
<PlusIcon />
|
||||||
<div className="text-sm2 pt-0.5 font-normal text-foreground">
|
<div className="text-sm2 pt-0.5 font-normal text-foreground">
|
||||||
@@ -119,8 +99,7 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
<>
|
<>
|
||||||
<button
|
<button
|
||||||
onClick={handleAddToCart}
|
onClick={handleAddToCart}
|
||||||
disabled={isSuccess && isLoading}
|
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors"
|
||||||
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
>
|
||||||
<PlusIcon className="text-foreground" />
|
<PlusIcon className="text-foreground" />
|
||||||
</button>
|
</button>
|
||||||
@@ -135,8 +114,7 @@ const MenuItem = ({ food }: MenuItemProps) => {
|
|||||||
</motion.div>
|
</motion.div>
|
||||||
<button
|
<button
|
||||||
onClick={handleRemoveFromCart}
|
onClick={handleRemoveFromCart}
|
||||||
disabled={isSuccess && isLoading}
|
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors"
|
||||||
className="bg-container hover:bg-container/60 active:bg-container/30 rounded-sm p-2 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
>
|
||||||
<MinusIcon className="text-foreground" />
|
<MinusIcon className="text-foreground" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
Reference in New Issue
Block a user