Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

usePrefetchInfiniteQuery.tsx

72 lines2.7 KB

1import { noop } from '@tanstack/query-core'
2import { useQueryClient } from './QueryClientProvider'
3​
4import type { DefaultError, QueryClient, QueryKey } from '@tanstack/query-core'
5import type { UsePrefetchInfiniteQueryOptions } from './types'
6​
7/**
8 * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render,
9 * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass
10 * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though
11 * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required unless
12 * a default query function has been defined.
13 *
14 * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
15 * as well as pageParam information, and should return a single variable that will be passed to your query
16 * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
17 *
18 * The prefetch is skipped if the query already has any cached state β€” including a `pending`/`error` state left
19 * over from a previous attempt β€” so calling this on every render is cheap and won't refetch data that's
20 * already there or already in flight.
21 *
22 * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use β€” everything you can pass to `queryClient.infiniteQuery`.
23 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
24 * be used.
25 * @returns `void` β€” nothing is returned.
26 *
27 * @example
28 * ```tsx
29 * import { Suspense } from 'preact/compat'
30 * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/preact-query'
31 *
32 * const projectsOptions = infiniteQueryOptions({
33 * queryKey: ['projects'],
34 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
35 * initialPageParam: 0,
36 * getNextPageParam: (lastPage) => lastPage.nextId,
37 * })
38 *
39 * function App() {
40 * // Fire the prefetch during render, before the suspense boundary below.
41 * usePrefetchInfiniteQuery(projectsOptions)
42 *
43 * return (
44 * <Suspense fallback={<h1>Loading projects...</h1>}>
45 * <Projects />
46 * </Suspense>
47 * )
48 * }
49 * ```
50 */
51export function usePrefetchInfiniteQuery<
52 TQueryFnData = unknown,
53 TError = DefaultError,
54 TData = TQueryFnData,
55 TQueryKey extends QueryKey = QueryKey,
56 TPageParam = unknown,
57>(
58 options: UsePrefetchInfiniteQueryOptions<
59 TQueryFnData,
60 TError,
61 TData,
62 TQueryKey,
63 TPageParam
64 >,
65 queryClient?: QueryClient,
66) {
67 const client = useQueryClient(queryClient)
68​
69 if (!client.getQueryState(options.queryKey)) {
70 void client.infiniteQuery(options).catch(noop)
71 }