Created
January 17, 2024 17:57
-
-
Save jasikpark/af105fd7ccba9b40cc7dc92155c61a18 to your computer and use it in GitHub Desktop.
`usePrefetchQuery` with types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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