import { type QueryKey, useQuery, type UseQueryOptions, type UseQueryResult, } from "@tanstack/react-query"; import { useSyncExternalStore } from "react"; import { getAuthenticatedSessionSnapshot, subscribeAuthenticatedSession, } from "./client"; 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 { useAuthenticatedQuery };