|
1 | | -export { useRateProductMutation } from "@/lib/api/marketing/{product-id}/use-rate-product-mutation"; |
| 1 | +import { useMutation, useQueryClient } from "@tanstack/react-query"; |
| 2 | + |
| 3 | +import { marketingQueryKeys } from "@/lib/api/marketing/marketing-query-keys"; |
| 4 | +import type { MarketingProductDto } from "@/lib/api/marketing/{product-id}/marketing-product-dto"; |
| 5 | +import { |
| 6 | + rateProductMutationOptions, |
| 7 | + type RateProductDto, |
| 8 | +} from "@/lib/api/marketing/{product-id}/rate-product-mutation"; |
| 9 | + |
| 10 | +interface MutationContext { |
| 11 | + previous: MarketingProductDto | undefined; |
| 12 | + productId: string; |
| 13 | +} |
| 14 | + |
| 15 | +export const useRateProductMutation = () => { |
| 16 | + const queryClient = useQueryClient(); |
| 17 | + |
| 18 | + const { mutateAsync, isPending } = useMutation< |
| 19 | + MarketingProductDto, |
| 20 | + Error, |
| 21 | + RateProductDto, |
| 22 | + MutationContext |
| 23 | + >({ |
| 24 | + ...rateProductMutationOptions, |
| 25 | + onMutate: async ({ productId, rating }) => { |
| 26 | + const queryKey = marketingQueryKeys.product(productId); |
| 27 | + await queryClient.cancelQueries({ queryKey }); |
| 28 | + |
| 29 | + const previous = queryClient.getQueryData<MarketingProductDto>(queryKey); |
| 30 | + |
| 31 | + if (previous) { |
| 32 | + const { rate: oldRate, count: oldCount } = previous.rating; |
| 33 | + const newCount = oldCount + 1; |
| 34 | + const newRate = |
| 35 | + Math.round(((oldRate * oldCount + rating) / newCount) * 100) / 100; |
| 36 | + |
| 37 | + queryClient.setQueryData<MarketingProductDto>(queryKey, { |
| 38 | + ...previous, |
| 39 | + rating: { rate: newRate, count: newCount }, |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + return { previous, productId }; |
| 44 | + }, |
| 45 | + onError: (_err, _vars, context) => { |
| 46 | + if (context?.previous) { |
| 47 | + queryClient.setQueryData( |
| 48 | + marketingQueryKeys.product(context.productId), |
| 49 | + context.previous |
| 50 | + ); |
| 51 | + } |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + const handler = (productId: string, rating: number) => |
| 56 | + mutateAsync({ productId, rating }); |
| 57 | + |
| 58 | + return [handler, isPending] as const; |
| 59 | +}; |
0 commit comments