All files / src/hooks/queries useUserAddressQuery.ts

63.63% Statements 7/11
69.23% Branches 9/13
66.66% Functions 2/3
70% Lines 7/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                                    1x       203x     38x       38x   37x             37x   37x            
// src/hooks/queries/useUserAddressQuery.ts
import { useQuery } from '@tanstack/react-query';
import { getUserAddress } from '../../services/apiClient';
import { queryKeys } from '../../config/queryKeys';
import type { Address } from '../../types';
 
/**
 * Query hook for fetching a user's address by ID.
 *
 * @param addressId - The ID of the address to fetch, or null/undefined if not available
 * @param enabled - Whether the query should run (default: true when addressId is provided)
 * @returns TanStack Query result with Address data
 *
 * @example
 * ```tsx
 * const { data: address, isLoading, error } = useUserAddressQuery(userProfile?.address_id);
 * ```
 */
export const useUserAddressQuery = (
  addressId: number | null | undefined,
  enabled: boolean = true,
) => {
  return useQuery({
    queryKey: queryKeys.userAddress(addressId ?? null),
    queryFn: async (): Promise<Address> => {
      Iif (!addressId) {
        throw new Error('Address ID is required');
      }
 
      const response = await getUserAddress(addressId);
 
      Iif (!response.ok) {
        const error = await response.json().catch(() => ({
          message: `Request failed with status ${response.status}`,
        }));
        throw new Error(error.message || 'Failed to fetch user address');
      }
 
      const json = await response.json();
      // API returns { success: true, data: {...} }, extract the data object
      return json.data ?? json;
    },
    enabled: enabled && !!addressId,
    staleTime: 1000 * 60 * 5, // 5 minutes - address data doesn't change frequently
  });
};