62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
import {
|
|
type QueryKey,
|
|
useQueries,
|
|
useQuery,
|
|
type UseQueryOptions,
|
|
type UseQueryResult,
|
|
} from "@tanstack/react-query";
|
|
import { useSyncExternalStore } from "react";
|
|
|
|
import {
|
|
getAuthenticatedSessionSnapshot,
|
|
subscribeAuthenticatedSession,
|
|
} from "./client";
|
|
|
|
function useAuthenticatedQueries<TData, TError, TQueryKey extends QueryKey>(
|
|
queries: UseQueryOptions<TData, TError, TData, TQueryKey>[],
|
|
) {
|
|
const hasSession = useHasAuthenticatedSession();
|
|
|
|
return useQueries({
|
|
queries: queries.map(
|
|
(options): UseQueryOptions<TData, TError, TData, TQueryKey> => ({
|
|
...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<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 { useAuthenticatedQueries, useAuthenticatedQuery };
|