All files / src/api/suppliers/hooks useSupplierByIdQuery.ts

100% Statements 59/59
66.66% Branches 4/6
100% Functions 2/2
100% Lines 59/59

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 48 49 50 51 52 53 54 55 56 57 58 59 601x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x  
/**
 * @file useSupplierByIdQuery.ts
 * @module api/suppliers/hooks/useSupplierByIdQuery
 *
 * @summary
 * React Query hook for loading a single supplier by ID.
 * Useful for edit dialogs and detail views.
 *
 * @enterprise
 * - Only fetches when supplierId is provided
 * - 1-minute cache reduces redundant API calls
 * - Graceful null handling for missing data
 */
 
import { useQuery } from '@tanstack/react-query';
import { getSuppliersPage } from '../supplierListFetcher';
import type { SupplierRow } from '../types';
 
/**
 * Hook to load a single supplier by ID.
 * Useful for edit dialogs that need to display current supplier data.
 *
 * @param supplierId - The ID of the supplier to load
 * @param enabled - Whether to fetch (defaults to true)
 * @returns React Query result with supplier data or null
 *
 * @remarks
 * Currently fetches via the list endpoint with search filter.
 * A dedicated GET /api/suppliers/:id endpoint would be more efficient.
 *
 * @example
 * ```typescript
 * const { data: supplier } = useSupplierByIdQuery(selectedSupplierId);
 *
 * return <TextField value={supplier?.name} />;
 * ```
 */
export const useSupplierByIdQuery = (
  supplierId: string | null,
  enabled: boolean = true,
) => {
  return useQuery<SupplierRow | null, Error>({
    queryKey: ['suppliers', 'byId', supplierId],
    queryFn: async () => {
      if (!supplierId) return null;
 
      const response = await getSuppliersPage({
        page: 1,
        pageSize: 100,
        q: supplierId,
      });
 
      return response.items.find((s) => s.id === supplierId) ?? null;
    },
    enabled: enabled && !!supplierId,
    staleTime: 60_000,
    gcTime: 5 * 60_000,
  });
};