import { type QueryKey, useQueries, useQuery, type UseQueryOptions, type UseQueryResult, } from "@tanstack/react-query"; import { useSyncExternalStore } from "react"; import { getAuthenticatedSessionSnapshot, subscribeAuthenticatedSession, } from "./client"; function useAuthenticatedQueries( queries: UseQueryOptions[], ) { const hasSession = useHasAuthenticatedSession(); return useQueries({ queries: queries.map( (options): UseQueryOptions => ({ ...options, enabled: query => hasSession && (typeof options.enabled === "function" ? options.enabled(query) : (options.enabled ?? true)), }), ), }); } function useAuthenticatedQuery< TQueryFunctionData = unknown, TError = Error, TData = TQueryFunctionData, TQueryKey extends QueryKey = QueryKey, >( options: UseQueryOptions, ): UseQueryResult { const hasSession = useHasAuthenticatedSession(); const enabled = options.enabled; return useQuery({ ...options, enabled: query => hasSession && (typeof enabled === "function" ? enabled(query) : (enabled ?? true)), }); } function useHasAuthenticatedSession() { return useSyncExternalStore( subscribeAuthenticatedSession, getAuthenticatedSessionSnapshot, getAuthenticatedSessionSnapshot, ); } export { useAuthenticatedQueries, useAuthenticatedQuery };