use-connections.ts1.5 KBView on GitHub
import { useSession } from '@/modules/auth/utils/auth-client';
import { useTRPC } from '@/providers/query-provider';
import { useQuery } from '@tanstack/react-query';

export const useConnections = (userId?: string) => {
  const trpc = useTRPC();
  const { data: session } = useSession();
  const connectionsQuery = useQuery(
    trpc.connections.list.queryOptions(userId ? { userId } : undefined, {
      // `connections.list` is a privateProcedure. Firing it before the session lands
      // just returns Unauthorized, and callers read the empty result as "no connections"
      // rather than "not asked yet" — which is how /onboarding lost its Gmail, meeting
      // and CRM steps. Matches the guard useActiveConnection already has.
      enabled: !!session,
    }),
  );
  return connectionsQuery;
};

export const useActiveConnection = () => {
  const trpc = useTRPC();
  const { data: session } = useSession();

  // Note: Admin viewing user cache isolation is handled by QueryProvider's queryKeyHashFn
  // which includes connectionId in the hash. The admin headers are also set per-request
  // via createTrpcClient(adminViewingUserId) in QueryProvider.
  const connectionsQuery = useQuery(
    trpc.connections.getDefault.queryOptions(void 0, {
      staleTime: 1000 * 60 * 60, // 1 hour
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      refetchOnReconnect: false,
      enabled: !!session, // Only fetch when session exists
    }),
  );

  return connectionsQuery;
};