Просмотр исходного кода

结账页运输方式与支付方式 --- v1

fogwind 2 дней назад
Родитель
Сommit
85dfc69cee

BIN
public/image/payment/afterpay.png


BIN
public/image/payment/credit.png


BIN
public/image/payment/klarna.png


BIN
public/image/payment/paypal.png


+ 9 - 0
src/app/(checkout)/checkout/_components/CheckoutPlaceOrder.tsx

@@ -0,0 +1,9 @@
+export default function CheckoutPlaceOrder() { 
+    return (
+        <>
+            <button className="flex items-center justify-center w-full h-12 bg-ly-green text-white rounded-3xl text-ly-16 font-bold">
+                Place Order
+            </button>
+        </>
+    );
+}

+ 15 - 0
src/app/(checkout)/checkout/_components/CheckoutShippingMethodLoading.tsx

@@ -0,0 +1,15 @@
+export default function CheckoutShippingMethodLoading() { 
+    return (
+        <div className="mt-3 w-full animate-pulse px-0">
+            <div className="group block relative box-border p-3 border-1 rounded-sm">
+                <p className="text-ly-13">
+                    <span className="text-ly-13 text-gray-300 bg-gray-300 font-bold mr-1">FREE</span>
+                    <span className="text-gray-300 bg-gray-300">USPS/FedEx/DHL/UPS</span>
+                </p>
+                <p className="text-ly-12 text-gray-300 bg-gray-300 w-40 mt-1">(2-5 business days)</p>
+
+                <div className="absolute top-1/2 -translate-y-1/2 right-3 bg-gray-300 w-4 h-4"></div>
+            </div>
+        </div>
+    );
+}

+ 83 - 39
src/app/(checkout)/checkout/_components/CheckoutWrapper.tsx

@@ -1,10 +1,10 @@
 "use client";
 "use client";
 
 
-import {useState, useEffect} from "react";
+import {useState, useEffect, useRef, Suspense} from "react";
 
 
 import { LoadingSpinner } from "@components/common/LoadingSpinner";
 import { LoadingSpinner } from "@components/common/LoadingSpinner";
-// import { useForm, SubmitHandler } from "react-hook-form"
-import { useForm, FormProvider } from "react-hook-form"
+import CheckoutShippingMethodLoading from "./CheckoutShippingMethodLoading";
+import { useForm, FormProvider } from "react-hook-form";
 
 
 import { 
 import { 
     Country,
     Country,
@@ -18,13 +18,23 @@ import AddressResultDisplayLoading from "./AddressResultDisplayLoading";
 import CheckoutAddressModal from "./CheckoutAddressModal";
 import CheckoutAddressModal from "./CheckoutAddressModal";
 import ShippingAddressCheckout from "./ShippingAddressCheckout";
 import ShippingAddressCheckout from "./ShippingAddressCheckout";
 import BillingAddressCheckout from "./BillingAddressCheckout";
 import BillingAddressCheckout from "./BillingAddressCheckout";
-// import CheckoutShippingMethod from "./CheckoutShippingMethod";
+import {ShippingMethodCheckout,RefShippingMethodsHandle} from "./ShippingMethodCheckout";
 import { useCustomToast } from "@/utils/hooks/useToast";
 import { useCustomToast } from "@/utils/hooks/useToast";
 import {useCheckoutAddress} from "@/utils/hooks/useCheckoutAddress"
 import {useCheckoutAddress} from "@/utils/hooks/useCheckoutAddress"
+import {useCheckoutPaymentMethod} from  "@/utils/hooks/useCheckoutPaymentMethod";
+import { useAppSelector,useAppDispatch } from "@/store/hooks";
+import { updateCart } from "@/store/slices/cart-slice";
+import { useCartDetail } from "@utils/hooks/useCartDetail";
+import PaymentMethodCheckout from "./PaymentMethodCheckout";
+import LoadingPaymentMethod from "./LoadingPaymentMethod";
+import CheckoutPlaceOrder from "./CheckoutPlaceOrder";
+
 /***
 /***
  * 不用useForShipping字段了
  * 不用useForShipping字段了
  * 以shipping address 为准,根据shippingaddress 设置billing address
  * 以shipping address 为准,根据shippingaddress 设置billing address
- * 保存完地址之后要重新获取运输方式和支付方式
+ * @todo 保存完地址之后要重新获取运输方式和支付方式
+ * @todo 变更运输方式后重新获取支付方式
+ * @todo redux本地存储购物车详情优化(slice定义修改;useCartDetail自定义hook修改;最后结账也统一优化购物车详情获取)
  */
  */
 
 
 /**
 /**
@@ -81,29 +91,7 @@ function generateSaveCheckoutAddressParam(formData: FullAddressFormData):CreateC
     };
     };
     
     
 }
 }
-/**
- * 对比shipping address与billing address的数据是否完全相同
- */
-/*function addressIsSame(billAddress: BillAddressFormData | null, shipAddress: ShipAddressFormData | null) {
-    if(billAddress === null && shipAddress === null) {
-        return true;
-    } else if(billAddress !== null && shipAddress !== null) {
-        return (
-           billAddress.billingEmail === shipAddress.shippingEmail &&
-           billAddress.billingFirstName === shipAddress.shippingFirstName &&
-           billAddress.billingLastName === shipAddress.shippingLastName &&
-           billAddress.billingCompanyName === shipAddress.shippingCompanyName &&
-           billAddress.billingAddress === shipAddress.shippingAddress &&
-           billAddress.billingCity === shipAddress.shippingCity &&
-           billAddress.billingState === shipAddress.shippingState &&
-           billAddress.billingCountry === shipAddress.shippingCountry &&
-           billAddress.billingPostcode === shipAddress.shippingPostcode &&
-           billAddress.billingPhoneNumber === shipAddress.shippingPhoneNumber 
-        );
-    } else {
-        return false;
-    }
-}*/
+
 export default function CheckoutWrapper({
 export default function CheckoutWrapper({
     loginEmail,
     loginEmail,
     countries
     countries
@@ -111,9 +99,22 @@ export default function CheckoutWrapper({
     loginEmail: string;
     loginEmail: string;
     countries: Country[]
     countries: Country[]
 }) {
 }) {
+    const dispatch = useAppDispatch();
+    const { getCartDetail } = useCartDetail();
+   
+    const { 
+        data: paymentMethodDatas,
+        loading: paymentMethodLoading,
+        error: paymentMethodError,
+        getPaymentMethod, 
+        savePaymentMethod 
+    } = useCheckoutPaymentMethod();
+
     const { showToast } = useCustomToast();
     const { showToast } = useCustomToast();
     const { getCheckoutAddress, saveCheckoutAddress } = useCheckoutAddress(loginEmail);
     const { getCheckoutAddress, saveCheckoutAddress } = useCheckoutAddress(loginEmail);
 
 
+    const methodShiippingRef = useRef<RefShippingMethodsHandle>(null);
+
 
 
     // useForm() 只会在组件初始化时读取一次 defaultValues
     // useForm() 只会在组件初始化时读取一次 defaultValues
     const addressForm = useForm<FullAddressFormData>({
     const addressForm = useForm<FullAddressFormData>({
@@ -124,7 +125,8 @@ export default function CheckoutWrapper({
     const [addressModalOpen, setAddressModalOpen] = useState(false);
     const [addressModalOpen, setAddressModalOpen] = useState(false);
     const [loadingData, setLoadingData] = useState(true);
     const [loadingData, setLoadingData] = useState(true);
     const [serverShippingAddress, setServerShippingAddress] = useState<ShipAddressFormData | null>(null);
     const [serverShippingAddress, setServerShippingAddress] = useState<ShipAddressFormData | null>(null);
-    const [serverBillingAddress, setServerBillingAddress] = useState<BillAddressFormData | null>(null);
+
+    const serverBillingAddress = useRef<BillAddressFormData | null>(null);
 
 
     const [addressSaving, setAddressSaving] = useState(false);
     const [addressSaving, setAddressSaving] = useState(false);
 
 
@@ -138,9 +140,8 @@ export default function CheckoutWrapper({
             setServerShippingAddress({
             setServerShippingAddress({
                 ...shippingAddress
                 ...shippingAddress
             });
             });
-            setServerBillingAddress({
-                ...billingAddress
-            });
+            serverBillingAddress.current = billingAddress;
+         
             setLoadingData(false);
             setLoadingData(false);
         }, ()=> {
         }, ()=> {
             setLoadingData(false);
             setLoadingData(false);
@@ -151,10 +152,10 @@ export default function CheckoutWrapper({
     const openAddressModal = () => {
     const openAddressModal = () => {
         setAddressModalOpen(true);
         setAddressModalOpen(true);
 
 
-        if(serverShippingAddress && serverBillingAddress) {
+        if(serverShippingAddress && serverBillingAddress.current) {
             addressForm.reset({
             addressForm.reset({
                 ...serverShippingAddress,
                 ...serverShippingAddress,
-                ...serverBillingAddress,
+                ...serverBillingAddress.current,
             });
             });
         }
         }
         
         
@@ -166,7 +167,8 @@ export default function CheckoutWrapper({
     };
     };
     const addressFormOnSubmit = async (formData: FullAddressFormData) => { 
     const addressFormOnSubmit = async (formData: FullAddressFormData) => { 
         // console.log('addressFormOnSubmit ---- ',formData); return;
         // console.log('addressFormOnSubmit ---- ',formData); return;
-        // 保存完地址之后还要重新请求地址,把保存后的地址id同步到表单里;还需要获取运输方式
+        // 保存完地址之后还要重新请求地址,把保存后的地址id同步到表单里;
+        // 还需要获取运输方式
 
 
         const saveAddressParam = generateSaveCheckoutAddressParam(formData);
         const saveAddressParam = generateSaveCheckoutAddressParam(formData);
         setAddressSaving(true);
         setAddressSaving(true);
@@ -174,6 +176,10 @@ export default function CheckoutWrapper({
 
 
             const res = await saveCheckoutAddress(saveAddressParam);
             const res = await saveCheckoutAddress(saveAddressParam);
             console.log('CREATE_CHECKOUT_ADDRESS res ====== ',res);
             console.log('CREATE_CHECKOUT_ADDRESS res ====== ',res);
+            if(methodShiippingRef.current) {
+                methodShiippingRef.current.reloadSHippingMethods();
+            }
+            
             const queryAddressRes = await getCheckoutAddress();
             const queryAddressRes = await getCheckoutAddress();
             if(queryAddressRes !== null) {
             if(queryAddressRes !== null) {
                 addressForm.resetField('shippingAddressId',{
                 addressForm.resetField('shippingAddressId',{
@@ -185,9 +191,8 @@ export default function CheckoutWrapper({
                 setServerShippingAddress({
                 setServerShippingAddress({
                     ...queryAddressRes.shippingAddress
                     ...queryAddressRes.shippingAddress
                 });
                 });
-                setServerBillingAddress({
-                    ...queryAddressRes.billingAddress
-                });
+                serverBillingAddress.current = queryAddressRes.billingAddress;
+
             }
             }
             setAddressModalOpen(false);
             setAddressModalOpen(false);
         } catch(err) {
         } catch(err) {
@@ -200,6 +205,22 @@ export default function CheckoutWrapper({
         }
         }
         
         
     };
     };
+
+
+    const handlePaymentMethodChange =  async (method: string,title: string) => { 
+        
+        const res = await savePaymentMethod({ paymentMethod: method });
+        console.log('savePaymentMethod res ====== ',res);
+        if(!res.error) {
+            // 更新paymentMethod paymentMethodTitle
+            dispatch(updateCart({
+                paymentMethod: method,
+                paymentMethodTitle: title
+            }));
+        } else {
+            showToast(res.msg, 'danger');
+        }
+    };
     // function tt() {
     // function tt() {
     //     const arr = [
     //     const arr = [
     //         ['US','3803800217'], 
     //         ['US','3803800217'], 
@@ -250,7 +271,30 @@ export default function CheckoutWrapper({
                     />
                     />
             </div>
             </div>
             <div className="mt-6 box-border px-4">
             <div className="mt-6 box-border px-4">
-                {/* <CheckoutShippingMethod /> */}
+                <h3 className="text-ly-24 font-medium">Shipping Method</h3>
+                {/* <Suspense fallback={<CheckoutShippingMethodLoading />}> */}
+                    <ShippingMethodCheckout ref={methodShiippingRef}  />
+                {/* </Suspense> */}
+            </div>
+
+            <div className="mt-6 box-border px-4">
+                <h3 className="text-ly-24 font-medium">Payment Method</h3>
+                { paymentMethodLoading ?
+                    <LoadingPaymentMethod />
+                :   
+                    <PaymentMethodCheckout 
+                        errorMsg={paymentMethodError}
+                        paymentMethods={paymentMethodDatas} 
+                        onPaymentMethodChange={handlePaymentMethodChange}
+                    />
+                }
+                
+            </div>
+            <div className="mt-3 box-border px-4">
+                <p className="text-ly-12 text-[#666666] leading-ly-20">By providing your information, you agree to Wiggins'sPrivacy Policyand Terms of Use.</p>
+                <div className="mt-6 w-full">
+                    <CheckoutPlaceOrder />
+                </div>
             </div>
             </div>
            
            
         </section> 
         </section> 

+ 13 - 0
src/app/(checkout)/checkout/_components/LoadingPaymentMethod.tsx

@@ -0,0 +1,13 @@
+export default function LoadingPaymentMethod() { 
+    return (
+        <div className="mt-3 w-full animate-pulse px-0">
+            <div className="group box-border flex items-center relative mt-3 p-3 rounded-sm">
+                <p className="pr-2 flex-initial h-8 w-12 bg-gray-300"></p>
+                <p className="text-ly-12 text-gray-300 bg-gray-300 ml-1">Paypay Smart Button</p>
+  
+
+                <div className="absolute top-1/2 -translate-y-1/2 right-3 bg-gray-300 w-4 h-4"></div>
+            </div>
+        </div>
+    );
+}

Разница между файлами не показана из-за своего большого размера
+ 105 - 0
src/app/(checkout)/checkout/_components/PaymentMethodCheckout.tsx


Разница между файлами не показана из-за своего большого размера
+ 175 - 0
src/app/(checkout)/checkout/_components/ShippingMethodCheckout.tsx


+ 0 - 2
src/app/(checkout)/checkout/page.tsx

@@ -1,7 +1,6 @@
 import { getServerSession } from "next-auth";
 import { getServerSession } from "next-auth";
 import { authOptions } from "@utils/auth";
 import { authOptions } from "@utils/auth";
 import { fullCacheGraphqlRequest} from "@/lib/graphql-fetch";
 import { fullCacheGraphqlRequest} from "@/lib/graphql-fetch";
-import CheckOut from "@/components/checkout";
 import CheckoutWrapper from "./_components/CheckoutWrapper";
 import CheckoutWrapper from "./_components/CheckoutWrapper";
 import { GET_COUNTRIES } from "@/graphql";
 import { GET_COUNTRIES } from "@/graphql";
 import { Country } from "@/types/checkout/type";
 import { Country } from "@/types/checkout/type";
@@ -49,7 +48,6 @@ export default async function Information({
                 loginEmail={session?.user?.email || ""}
                 loginEmail={session?.user?.email || ""}
                 countries={countriesData?.countries || []}
                 countries={countriesData?.countries || []}
             />
             />
-            <CheckOut step={step} />
         </>
         </>
     );
     );
   
   

+ 4 - 4
src/app/(checkout)/layout.tsx

@@ -1,4 +1,4 @@
-import Navbar from "@components/layout/navbar";
+import TitleHeader from "@components/layout/navbar/TitleHeader";
 import { ReactNode } from "react";
 import { ReactNode } from "react";
 export default async function RootLayout({
 export default async function RootLayout({
   children,
   children,
@@ -7,9 +7,9 @@ export default async function RootLayout({
 }) {
 }) {
   return (
   return (
     <>
     <>
-      <div className="block lg:hidden">
-        <Navbar />
-      </div>
+
+      <TitleHeader title="Checkout" />
+
       <main className="mx-auto w-full">
       <main className="mx-auto w-full">
         {children}
         {children}
       </main>
       </main>

+ 0 - 1
src/app/api/graphql/route.ts

@@ -148,7 +148,6 @@ export async function POST(req: NextRequest) {
             data: response.body.data,
             data: response.body.data,
         });
         });
     } catch (error) {
     } catch (error) {
-        console.log('response err------ ', error);
         if (isBagistoError(error)) {
         if (isBagistoError(error)) {
             return NextResponse.json(
             return NextResponse.json(
                 {
                 {

+ 5 - 5
src/components/checkout/index.tsx

@@ -26,9 +26,9 @@ const CheckOut = ({ step }: CheckOutProps) => {
   const selectedPaymentTitle = cartItems?.paymentMethodTitle;
   const selectedPaymentTitle = cartItems?.paymentMethodTitle;
   useScrollToTop();
   useScrollToTop();
 
 
-  useEffect(() => {
-    getCartDetail();
-  }, [getCartDetail]);
+  // useEffect(() => {
+  //   getCartDetail();
+  // }, [getCartDetail]);
 
 
 
 
 
 
@@ -43,9 +43,9 @@ const CheckOut = ({ step }: CheckOutProps) => {
               billingAddress={billingAddress}
               billingAddress={billingAddress}
               currentStep={step}
               currentStep={step}
               selectedPayment={selectedPayment}
               selectedPayment={selectedPayment}
-              selectedPaymentTitle={selectedPaymentTitle}
+              selectedPaymentTitle={selectedPaymentTitle || ''}
               selectedShippingRate={selectedShippingRate}
               selectedShippingRate={selectedShippingRate}
-              selectedShippingRateTitle={selectedShippingRateTitle}
+              selectedShippingRateTitle={selectedShippingRateTitle || ''}
               shippingAddress={shippingAddress}
               shippingAddress={shippingAddress}
             />
             />
           )}
           )}

+ 16 - 0
src/components/layout/navbar/TitleHeader.tsx

@@ -0,0 +1,16 @@
+"use client";
+import { useRouter } from 'next/navigation';
+
+export default function TitleHeader({title}: {title: string}) {
+    const router = useRouter();
+    return (
+        <header className="sticky top-0 z-10 w-full">
+            <div className="relative w-full h-15 flex items-center justify-center bg-neutral-50 text-ly-16">
+                <div className="absolute left-4 w-6 h-6" onClick={() => router.back()}>
+                    <svg className="block w-6 h-6" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="24" height="24" viewBox="0 0 24 24" fill="none"><path    stroke="rgba(0, 0, 0, 1)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="square"  d="M14.5 18L8.5 12L14.5 6"></path></svg>
+                </div>
+                {title}
+            </div>
+        </header>
+    );
+}

+ 3 - 2
src/graphql/checkout/mutations/CreateCheckoutPaymentMethod.ts

@@ -1,6 +1,7 @@
-import { gql } from "@apollo/client";
+import { gql, TypedDocumentNode } from "@apollo/client";
+import { CreateCheckoutPaymentMethodResponse } from "@/types/checkout/type";
 
 
-export const CREATE_CHECKOUT_PAYMENT_METHODS = gql`
+export const CREATE_CHECKOUT_PAYMENT_METHODS: TypedDocumentNode<CreateCheckoutPaymentMethodResponse> = gql`
   mutation CreateCheckoutPaymentMethod(
   mutation CreateCheckoutPaymentMethod(
     $paymentMethod: String!
     $paymentMethod: String!
     $successUrl: String
     $successUrl: String

+ 3 - 2
src/graphql/checkout/mutations/CreateCheckoutShippingMethod.ts

@@ -1,6 +1,7 @@
-import { gql } from "@apollo/client";
+import { gql, TypedDocumentNode } from "@apollo/client";
+import {CreateCheckoutShippingMethodData} from "@/types/checkout/type";
 
 
-export const CREATE_CHECKOUT_SHIPPING_METHODS = gql`
+export const CREATE_CHECKOUT_SHIPPING_METHODS: TypedDocumentNode<CreateCheckoutShippingMethodData> = gql`
   mutation CreateCheckoutShippingMethod(
   mutation CreateCheckoutShippingMethod(
     $shippingMethod: String!
     $shippingMethod: String!
   ) {
   ) {

+ 3 - 2
src/graphql/checkout/queries/GetCheckoutPaymentMethods.ts

@@ -1,6 +1,7 @@
-import { gql } from "@apollo/client";
+import { gql,TypedDocumentNode } from "@apollo/client";
+import { CheckoutPaymentMethodsData } from "@/types/checkout/type";
 
 
-export const GET_CHECKOUT_PAYMENT_METHODS = gql`
+export const GET_CHECKOUT_PAYMENT_METHODS: TypedDocumentNode<CheckoutPaymentMethodsData> = gql`
   query CheckoutPaymentMethods {
   query CheckoutPaymentMethods {
     collectionPaymentMethods {
     collectionPaymentMethods {
       id
       id

+ 5 - 2
src/graphql/checkout/queries/GetCheckoutShippingRates.ts

@@ -1,14 +1,17 @@
-import { gql } from "@apollo/client";
+import { gql, TypedDocumentNode } from "@apollo/client";
+import {GetCheckoutShippingRatesData} from "@/types/checkout/type";
 
 
-export const GET_CHECKOUT_SHIPPING_RATES = gql`
+export const GET_CHECKOUT_SHIPPING_RATES: TypedDocumentNode<GetCheckoutShippingRatesData> = gql`
   query CheckoutShippingRates {
   query CheckoutShippingRates {
     collectionShippingRates {
     collectionShippingRates {
+      _id
       id
       id
       code
       code
       description
       description
       method
       method
       price
       price
       label
       label
+      formattedPrice
     }
     }
   }
   }
 `;
 `;

+ 1 - 1
src/lib/graphql-fetch.ts

@@ -149,7 +149,7 @@ export async function graphqlRequest<
       // Promise-based APIs (e.g. client.query, client.mutate) - Errors either reject the promise or are returned in the result as the error field.
       // Promise-based APIs (e.g. client.query, client.mutate) - Errors either reject the promise or are returned in the result as the error field.
       // 如果错误被reject 则会进入catch
       // 如果错误被reject 则会进入catch
       const result: ApolloClient.QueryResult<TData> = await client.query(queryOption);
       const result: ApolloClient.QueryResult<TData> = await client.query(queryOption);
-      console.log('graphqlRequest network-only result ---- ', result);
+
       resData = result.data || null;
       resData = result.data || null;
       return {data: resData, error: result.error? result.error.message : '' };
       return {data: resData, error: result.error? result.error.message : '' };
   } catch (error) {
   } catch (error) {

+ 1 - 1
src/utils/bagisto/index.ts

@@ -194,7 +194,7 @@ export async function bagistoFetch<T>({
     // let cc = await cookies();
     // let cc = await cookies();
     // console.log('bagistoFetch --- url:', GRAPHQL_URL,isCookies);
     // console.log('bagistoFetch --- url:', GRAPHQL_URL,isCookies);
     // console.log('bagistoFetch --- queryString:', queryString);
     // console.log('bagistoFetch --- queryString:', queryString);
-    console.log('bagistoFetch --- baseHeaders:', baseHeaders);
+    // console.log('bagistoFetch --- baseHeaders:', baseHeaders);
     // console.log('bagistoFetch --- cookies:', cc.getAll());
     // console.log('bagistoFetch --- cookies:', cc.getAll());
     // console.log('bagistoFetch --- variables:', variables);
     // console.log('bagistoFetch --- variables:', variables);
     const result = await fetch(GRAPHQL_URL, {
     const result = await fetch(GRAPHQL_URL, {

+ 98 - 0
src/utils/hooks/useCheckoutPaymentMethod.ts

@@ -0,0 +1,98 @@
+"use client";
+
+import { useEffect, useState } 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 getPaymentMethod = (
+        resolveCallback: (res:PaymentMethodsResult) => void = () => {}, 
+        rejectCallback: (res: PaymentMethodsResult) => void = ()=> {}
+    ) => {
+        return apolloClient.query({
+            query: GET_CHECKOUT_PAYMENT_METHODS,
+            fetchPolicy: "no-cache",
+            context: {
+                fetchOptions: {
+                    cache: 'no-store',
+                },
+        
+            }
+        }).then((res) => {
+            const shippingMethods =  res.data?.collectionPaymentMethods || [];
+            const resData: PaymentMethodsResult = {
+                data: shippingMethods,
+                msg: '',
+                error: false
+            };
+            
+            console.log('GET_CHECKOUT_paymentmethod res ---- ',shippingMethods);
+            resolveCallback(resData);
+            return resData;
+        
+        }).catch((err) => {
+            console.error('GET_CHECKOUT_paymentmethod error ---- ',err);
+            const resData: PaymentMethodsResult = {
+                data: [],
+                msg: err.message,
+                error: true
+            };
+            rejectCallback(resData);
+            return resData;
+        });
+    };
+
+    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((resolveData) => {
+            const methodsData = resolveData.data;
+            setData(methodsData);
+            setLoading(false);
+        }, (rejectData) => {
+            setError(rejectData.msg);
+            setLoading(false);
+        });
+    }, []);
+
+    return {
+        data,
+        loading,
+        error,
+        getPaymentMethod,
+        savePaymentMethod
+    };
+}

+ 64 - 0
src/utils/hooks/useCheckoutShippingMethod.ts

@@ -0,0 +1,64 @@
+"use client";
+
+import { GET_CHECKOUT_SHIPPING_RATES, CREATE_CHECKOUT_SHIPPING_METHODS } from "@/graphql";
+import {useApolloClient} from "@apollo/client/react";
+import {CheckoutShippingRate, CreateCheckoutShippingMethodVariables} from "@/types/checkout/type";
+
+interface ShippingMethodsResult {
+    data: CheckoutShippingRate[];
+    msg: string;
+    error: boolean;
+}
+export function useCheckoutShippingMethod() {
+    const apolloClient = useApolloClient();
+
+    const getShippingMethod = (
+        resolveCallback: (res:ShippingMethodsResult) => void = () => {}, 
+        rejectCallback: (res: ShippingMethodsResult) => void = ()=> {}
+    ) => {
+        return apolloClient.query({
+            query: GET_CHECKOUT_SHIPPING_RATES,
+            fetchPolicy: "no-cache",
+            context: {
+                fetchOptions: {
+                    cache: 'no-store',
+                },
+        
+            }
+        }).then((res) => {
+            const shippingMethods =  res.data?.collectionShippingRates || [];
+            const resData: ShippingMethodsResult = {
+                data: shippingMethods,
+                msg: '',
+                error: false
+            };
+            
+            console.log('GET_CHECKOUT_shippingmethod res ---- ',shippingMethods);
+            resolveCallback(resData);
+            return resData;
+        
+        }).catch((err) => {
+            console.error('GET_CHECKOUT_shippingmethod error ---- ',err);
+            const resData: ShippingMethodsResult = {
+                data: [],
+                msg: err.message,
+                error: true
+            };
+            rejectCallback(resData);
+            return resData;
+        });
+    };
+
+    const saveShippingMethod = (params: CreateCheckoutShippingMethodVariables) => {
+        return apolloClient.mutate({
+            mutation: CREATE_CHECKOUT_SHIPPING_METHODS,
+            variables:params,
+        });
+    };
+
+
+    return {
+        getShippingMethod,
+        saveShippingMethod
+    };
+}

+ 2 - 2
src/utils/hooks/useGuestCartToken.ts

@@ -15,9 +15,9 @@ export const useGuestCartToken = () => {
   const [token, setToken] = useState(() => {
   const [token, setToken] = useState(() => {
       const cookieToken = getCookie(GUEST_CART_TOKEN);
       const cookieToken = getCookie(GUEST_CART_TOKEN);
       let guestCartToken: string | null = null;
       let guestCartToken: string | null = null;
-      console.log("cookieToken -----1 ", cookieToken);
+
       if (cookieToken) {
       if (cookieToken) {
-        console.log("cookieToken -----2 ", cookieToken);
+
         const isGuest = getCookie(IS_GUEST) !== "false";
         const isGuest = getCookie(IS_GUEST) !== "false";
         const decoded = decodeJWT<{
         const decoded = decodeJWT<{
           sessionToken: string;
           sessionToken: string;