| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- "use client";
- import { useEffect, useState, useRef, useCallback } from "react";
- import { GET_CHECKOUT_PAYMENT_METHODS, CREATE_CHECKOUT_PAYMENT_METHODS } from "@/graphql";
- import {useApolloClient} from "@apollo/client/react";
- import {CheckoutPaymentMethod, CreateCheckoutPaymentMethodVariables} from "@/types/checkout/type";
- interface PaymentMethodsResult {
- data: CheckoutPaymentMethod[];
- msg: string;
- error: boolean;
- }
- export function useCheckoutPaymentMethod() {
- const apolloClient = useApolloClient();
- const [data, setData] = useState<CheckoutPaymentMethod[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string|null>(null);
- const isIntRef = useRef(true);
- const getPaymentMethod = useCallback(() => {
- if(!isIntRef.current) {
- setLoading(true);
- }
- return apolloClient.query({
- query: GET_CHECKOUT_PAYMENT_METHODS,
- fetchPolicy: "no-cache",
- context: {
- fetchOptions: {
- cache: 'no-store',
- },
-
- }
- }).then((res) => {
- if(isIntRef.current) {
- isIntRef.current = false;
- }
- const paymentMethods = res.data?.collectionPaymentMethods || [];
- const resData: PaymentMethodsResult = {
- data: paymentMethods,
- msg: '',
- error: false
- };
- setData(resData.data);
- setLoading(false);
-
- console.log('GET_CHECKOUT_paymentmethod res ---- ',paymentMethods);
-
- return resData;
-
- }).catch((err) => {
- if(isIntRef.current) {
- isIntRef.current = false;
- }
- console.error('GET_CHECKOUT_paymentmethod error ---- ',err);
- const resData: PaymentMethodsResult = {
- data: [],
- msg: err.message,
- error: true
- };
- setError(resData.msg);
- setLoading(false);
-
- return resData;
- });
- },[apolloClient]);
- const savePaymentMethod = (params: CreateCheckoutPaymentMethodVariables) => {
- return apolloClient.mutate({
- mutation: CREATE_CHECKOUT_PAYMENT_METHODS,
- variables:params,
- }).then((res) => {
- const resData = {
- data: res.data?.createCheckoutPaymentMethod?.checkoutPaymentMethod,
- msg: '',
- error: false
- };
-
- return resData;
-
- }).catch((err) => {
- const resData = {
- data: null,
- msg: err.message,
- error: true
- };
-
- return resData;
- });
- };
- useEffect(() => {
- getPaymentMethod();
- // getPaymentMethod((resolveData) => {
- // const methodsData = resolveData.data;
- // setData(methodsData);
- // setLoading(false);
- // }, (rejectData) => {
- // setError(rejectData.msg);
- // setLoading(false);
- // });
- }, [getPaymentMethod]);
- return {
- data,
- loading,
- error,
- getPaymentMethod,
- savePaymentMethod
- };
- }
|