import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; import { listMyOrganizations } from "../../../shared/api/endpoints/organization/organization"; import type { Session } from "../../../shared/api/schemas"; import { needDirectoryPageSize, needQueryKeys } from "../model/query-keys"; import { isNeedSessionCurrent } from "./session"; /** Reads the signed-in account's organization directory for need context checks. */ export function useNeedOrganizationDirectory(session: Session | undefined, enabled: boolean) { const queryClient = useQueryClient(); const accountId = session?.account.id; const scopedAccountId = accountId ?? "no-session"; const csrfToken = session?.csrf_token; return useInfiniteQuery({ queryKey: needQueryKeys.directory(scopedAccountId), initialPageParam: undefined as string | undefined, queryFn: async ({ pageParam, signal }) => { if (!isNeedSessionCurrent(queryClient, session)) throw new Error("The session changed before the directory request."); const result = await listMyOrganizations( { limit: needDirectoryPageSize, ...(pageParam ? { cursor: pageParam } : {}) }, { signal }, ); if (!isNeedSessionCurrent(queryClient, session)) throw new Error("The session changed during the directory request."); return result; }, getNextPageParam: (lastPage) => lastPage.page.has_more ? (lastPage.page.next_cursor ?? undefined) : undefined, enabled: enabled && accountId !== undefined && csrfToken !== undefined, gcTime: 0, staleTime: 0, refetchOnMount: "always", refetchOnWindowFocus: "always", retry: false, }); }