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

usePrefetchInfiniteQuery.tsx

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