useAddress.ts 915 B

12345678910111213141516171819202122232425262728293031323334
  1. "use client";
  2. import { GET_CHECKOUT_ADDRESSES } from "@/graphql";
  3. import { CheckoutAddressNode, GetCheckoutAddressesData } from "@/types/checkout/type";
  4. import { useLazyQuery } from "@apollo/client/react";
  5. import { useCallback } from "react";
  6. export const useAddress = () => {
  7. const [fetchAddresses, { data, loading: isLoading, refetch }] = useLazyQuery<GetCheckoutAddressesData>(
  8. GET_CHECKOUT_ADDRESSES,
  9. {
  10. fetchPolicy: "cache-first",
  11. notifyOnNetworkStatusChange: true,
  12. }
  13. );
  14. const getAddresses = useCallback(async () => {
  15. try {
  16. await fetchAddresses();
  17. } catch (error) {
  18. console.error("Error fetching addresses:", error);
  19. }
  20. }, [fetchAddresses]);
  21. return {
  22. addresses:
  23. data?.collectionGetCheckoutAddresses?.edges?.map(
  24. (edge: { node: CheckoutAddressNode }) => edge.node
  25. ) || [],
  26. isLoading,
  27. refetch,
  28. getAddresses,
  29. };
  30. };