42 lines
965 B
TypeScript
42 lines
965 B
TypeScript
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<TQueryFunctionData, TError, TData, TQueryKey>,
|
|
): UseQueryResult<TData, TError> {
|
|
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 };
|