Skip to content

Instantly share code, notes, and snippets.

@jasikpark
Created January 17, 2024 17:57
Show Gist options
  • Save jasikpark/af105fd7ccba9b40cc7dc92155c61a18 to your computer and use it in GitHub Desktop.
Save jasikpark/af105fd7ccba9b40cc7dc92155c61a18 to your computer and use it in GitHub Desktop.
`usePrefetchQuery` with types
import { useQueryClient, type DefaultError, type FetchQueryOptions, type QueryKey } from '@tanstack/react-query';
// Type specified by `ensureQueryData` definition.
// Pulled from <https://tanstack.com/query/latest/docs/react/guides/prefetching>
export function usePrefetchQuery<
TQueryFnData,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, { enabled = false }: { enabled?: boolean } = {}) {
const queryClient = useQueryClient();
// This happens in render, but is safe to do because ensureQueryData
// only fetches if there is no data in the cache for this query. This
// means we know no observers are watching the data so the side effect
// is not observable, which is safe.
if (enabled) {
void queryClient.ensureQueryData(options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment