use-contacts.ts907 BView on GitHub
import { useQuery } from '@tanstack/react-query';
import { useTRPC } from '@/providers/query-provider';

/**
 * Shared hook for fetching and caching all CRM contacts.
 * Used across recipient autosuggest and event attendee inputs.
 * 
 * All contacts are prefetched once and cached for 5 minutes,
 * with client-side filtering for instant search results.
 * 
 * @param enabled - Whether to fetch contacts (default: true). Set to false for lazy loading.
 * @returns Query result with extracted contacts array and total count
 */
export function useContacts(enabled = true) {
  const trpc = useTRPC();

  const result = useQuery({
    ...trpc.crm.listContacts.queryOptions({
      limit: 1000,
    }),
    enabled,
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
    gcTime: Infinity,
  });

  return {
    ...result,
    contacts: result.data?.contacts ?? [],
    total: result.data?.total ?? 0,
  };
}