useAddToCart.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. "use client";
  2. import { useCustomToast } from "./useToast";
  3. import { useAppDispatch } from "@/store/hooks";
  4. import { addItem, clearCart } from "@/store/slices/cart-slice";
  5. import { isObject } from "@utils/type-guards";
  6. import { getCartToken } from "@utils/getCartToken";
  7. import { getCookie } from "@utils/cookie-tools";
  8. import { useGuestCartToken } from "./useGuestCartToken";
  9. import { IS_GUEST } from "@/utils/constants";
  10. import { useMutation } from "@apollo/client/react";
  11. import {
  12. CREATE_ADD_PRODUCT_IN_CART,
  13. REMOVE_CART_ITEM,
  14. UPDATE_CART_ITEM,
  15. } from "@/graphql";
  16. import { AddToCartData, RemoveCartItemData } from "@/types/cart/type";
  17. export const useAddProduct = () => {
  18. const dispatch = useAppDispatch();
  19. const { createGuestToken, resetGuestToken } = useGuestCartToken();
  20. const { showToast } = useCustomToast();
  21. const [mutateAsync, { loading: isCartLoading }] = useMutation<AddToCartData>(
  22. CREATE_ADD_PRODUCT_IN_CART,
  23. {
  24. onCompleted: (res) => {
  25. const responseData = res?.createAddProductInCart?.addProductInCart;
  26. if (!responseData?.success) {
  27. showToast(responseData?.message || "Error adding to cart", "danger");
  28. return;
  29. }
  30. if (responseData) {
  31. if (responseData.success) {
  32. dispatch(addItem(responseData as any));
  33. showToast("Product added to cart successfully", "success");
  34. }
  35. }
  36. },
  37. onError: (err) => {
  38. showToast(err?.message ?? "Error", "danger");
  39. },
  40. },
  41. );
  42. const onAddToCart = async ({
  43. productId,
  44. quantity,
  45. variantId
  46. }: {
  47. productId: string;
  48. quantity: number;
  49. variantId?: number;
  50. token?: string;
  51. cartId?: number | string;
  52. }) => {
  53. // Ensure token exists - create if needed
  54. let token = getCartToken(); // 从cookie获取token
  55. if (!token) {
  56. token = await createGuestToken();
  57. if (!token) {
  58. showToast("Failed to create cart session", "danger");
  59. return;
  60. }
  61. }
  62. let param : { productId: number; quantity:number; variantId?: number; } = {
  63. productId: parseInt(productId),
  64. quantity,
  65. };
  66. if(variantId) {
  67. param.variantId = variantId;
  68. }
  69. let result = await mutateAsync({
  70. variables: param,
  71. });
  72. return {
  73. data: result.data,
  74. error: result.error,
  75. };
  76. };
  77. //--------Remove Cart Product Quantity--------//
  78. const [removeFromCart, { loading: isRemoveLoading }] = useMutation<RemoveCartItemData>(
  79. REMOVE_CART_ITEM,
  80. {
  81. onCompleted: async (response) => {
  82. const responseData = response?.createRemoveCartItem?.removeCartItem;
  83. if (isObject(responseData)) {
  84. const message = "Cart item removed successfully";
  85. dispatch(addItem(responseData as any));
  86. showToast(message as string, "warning");
  87. if (!responseData?.itemsQty) {
  88. dispatch(clearCart());
  89. const isGuest = getCookie(IS_GUEST);
  90. if (isGuest === "true") {
  91. resetGuestToken();
  92. }
  93. }
  94. } else {
  95. showToast("Something went wrong", "warning");
  96. }
  97. },
  98. onError: (error) => {
  99. showToast(error?.message as string, "danger");
  100. },
  101. },
  102. );
  103. const onAddToRemove = async (productId: string) => {
  104. await removeFromCart({
  105. variables: {
  106. cartItemId: parseInt(productId),
  107. },
  108. });
  109. };
  110. //---------Update Cart Product Quantity--------//
  111. const [updateCartItem, { loading: isUpdateLoading }] = useMutation(
  112. UPDATE_CART_ITEM,
  113. {
  114. onCompleted: (response: any) => {
  115. const responseData = response?.createUpdateCartItem?.updateCartItem;
  116. if (isObject(responseData)) {
  117. dispatch(addItem(responseData as any));
  118. } else {
  119. showToast("Something went wrong!", "warning");
  120. }
  121. },
  122. onError: (error) => {
  123. showToast(error?.message as string, "danger");
  124. },
  125. },
  126. );
  127. const onUpdateCart = async ({
  128. cartItemId,
  129. quantity,
  130. }: {
  131. cartItemId: number;
  132. quantity: number;
  133. }) => {
  134. if (quantity < 1) {
  135. showToast("Quantity must be at least 1", "warning");
  136. return;
  137. }
  138. await updateCartItem({
  139. variables: {
  140. cartItemId: cartItemId,
  141. quantity,
  142. },
  143. });
  144. };
  145. return {
  146. isCartLoading,
  147. onAddToCart,
  148. isRemoveLoading,
  149. onAddToRemove,
  150. onUpdateCart,
  151. isUpdateLoading,
  152. };
  153. };