Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active May 6, 2022 01:23
Show Gist options
  • Save karol-majewski/14b5e411529ee4139985ba6b38d6117b to your computer and use it in GitHub Desktop.
Save karol-majewski/14b5e411529ee4139985ba6b38d6117b to your computer and use it in GitHub Desktop.
Easy prefetching with react-query
import { FetchQueryOptions, PayloadType, PrefetchableHook, useQueryClient } from 'react-query';
import { useDeepCompareEffect } from 'react-use';
/**
* Prefetches a query. Cancels any outgoing queries on unmount.
*
* @param hook Hook that returns a `UseQueryResult`.
* @param dependencies List of parameters required to build the key for the hook.
* @param options
*
* @example
*
* ```ts
* usePrefetch(useRepository, [])
* usePrefetch(useSearch, [term, filters])
* usePrefetch(useSearch, [term, filters], { staleTime: 60 * 1000 })
* ```
*
* @see https://react-query.tanstack.com/reference/QueryClient#queryclientprefetchquery
*/
export function usePrefetch<T extends PrefetchableHook>(
hook: T,
dependencies: Parameters<T['getKey']>,
options?: Omit<FetchQueryOptions<PayloadType<T>>, 'queryKey' | 'queryFn'>
): void {
const queryClient = useQueryClient();
const { getKey, queryFn } = hook;
useDeepCompareEffect(() => {
const queryKey = getKey(...dependencies);
queryClient.prefetchQuery({ queryKey, queryFn, ...options });
return () => {
queryClient.cancelQueries(queryKey, { exact: true });
};
}, [getKey, options, queryClient, queryFn]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment