useMergeCart.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. "use client";
  2. import { useMutation } from "@apollo/client/react";
  3. import { useAppDispatch } from "@/store/hooks";
  4. import { addItem } from "@/store/slices/cart-slice";
  5. import { CREATE_MERGE_CART } from "@/graphql";
  6. import { GUEST_CART_ID } from "@/utils/constants";
  7. import { setCookie } from "@utils/cookie-tools";
  8. import { formatCartDetail } from "@/utils/cartDetailTools";
  9. export function useMergeCart() {
  10. const dispatch = useAppDispatch();
  11. const [mergeCart, { loading: isLoading }] = useMutation(CREATE_MERGE_CART, {
  12. onCompleted: (response) => {
  13. const responseData = response?.createMergeCart?.mergeCart;
  14. if (!responseData) {
  15. return;
  16. }
  17. const cartId = responseData?.id ?? null;
  18. if (cartId !== null && typeof cartId !== "undefined") {
  19. setCookie(GUEST_CART_ID, String(cartId));
  20. }
  21. const cartDetail = formatCartDetail(responseData);
  22. dispatch(addItem(cartDetail));
  23. },
  24. onError: (_error) => {
  25. },
  26. });
  27. return {
  28. mergeCart,
  29. isLoading,
  30. };
  31. }