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

usePrefetchInfiniteQuery.ts

145 lines4.8 KB

1import { noop } from '@tanstack/query-core'
2import { getCurrentScope, unref, watchEffect } from 'vue-demi'
3import { useQueryClient } from './useQueryClient'
4import { cloneDeepUnref } from './utils'
5import type {
6 DefaultError,
7 DistributiveOmit,
8 InfiniteData,
9 InfiniteQueryExecuteOptions,
10 QueryKey,
11 SkipToken,
12} from '@tanstack/query-core'
13import type { QueryClient } from './queryClient'
14import type { MaybeRefDeep, MaybeRefOrGetter } from './types'
15​
16/**
17 * The options accepted by `usePrefetchInfiniteQuery` β€” everything you can pass to `queryClient.infiniteQuery`,
18 * except that `queryFn` can't be `skipToken`.
19 */
20export type UsePrefetchInfiniteQueryOptions<
21 TQueryFnData,
22 TError,
23 TData,
24 TQueryKey extends QueryKey,
25 TPageParam,
26> = DistributiveOmit<
27 InfiniteQueryExecuteOptions<
28 TQueryFnData,
29 TError,
30 TData,
31 TQueryKey,
32 TPageParam
33 >,
34 'queryFn'
35> & {
36 queryFn?: Exclude<
37 InfiniteQueryExecuteOptions<
38 TQueryFnData,
39 TError,
40 TData,
41 TQueryKey,
42 TPageParam
43 >['queryFn'],
44 SkipToken
45 >
47​
48/**
49 * Checks whether an option was passed as a getter function.
50 * @param value - The option value.
51 * @returns `true` if `value` is a function.
52 */
53function isGetter<T>(value: MaybeRefOrGetter<T>): value is () => T {
54 return typeof value === 'function'
56​
57/**
58 * `usePrefetchInfiniteQuery` does not return anything β€” it fires a prefetch as a reactive side effect, useful
59 * for kicking off a fetch ahead of the component that will actually render the data with `useInfiniteQuery`.
60 * You can pass everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`,
61 * though `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required
62 * unless a default query function has been defined.
63 *
64 * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages,
65 * as well as pageParam information, and should return a single variable that will be passed to your query
66 * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available.
67 *
68 * The prefetch is skipped if the query already has any cached state β€” including a `pending`/`error` state left
69 * over from a previous attempt β€” so it won't refetch data that's already there or already in flight. It
70 * re-runs whenever a reactive dependency in `options` (built with `infiniteQueryOptions`, for example) changes.
71 *
72 * Fire this during render, before a suspense boundary that wraps a component using `useInfiniteQuery`'s
73 * `suspense()` β€” see the {@link https://tanstack.com/query/latest/docs/framework/vue/guides/suspense | Suspense guide}.
74 * @param options - A `ref`, plain value, or reactive getter resolving to the
75 * {@link UsePrefetchInfiniteQueryOptions} to use β€” everything you can pass to `queryClient.infiniteQuery`.
76 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
77 * will be used.
78 * @example
79 * ```vue
80 * <script setup lang="ts">
81 * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/vue-query'
82 * import Projects from './Projects.vue'
83 *
84 * const projectsOptions = infiniteQueryOptions({
85 * queryKey: ['projects'],
86 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
87 * initialPageParam: 0,
88 * getNextPageParam: (lastPage) => lastPage.nextId,
89 * })
90 *
91 * // Fire the prefetch as soon as this component runs, before `Projects` mounts and calls `useInfiniteQuery`.
92 * usePrefetchInfiniteQuery(projectsOptions)
93 * </script>
94 *
95 * <template>
96 * <Projects />
97 * </template>
98 * ```
99 */
100export function usePrefetchInfiniteQuery<
101 TQueryFnData = unknown,
102 TError = DefaultError,
103 TData = InfiniteData<TQueryFnData>,
104 TQueryKey extends QueryKey = QueryKey,
105 TPageParam = unknown,
106>(
107 options: MaybeRefOrGetter<
108 MaybeRefDeep<
109 UsePrefetchInfiniteQueryOptions<
110 TQueryFnData,
111 TError,
112 TData,
113 TQueryKey,
114 TPageParam
115 >
116 >
117 >,
118 queryClient?: QueryClient,
119): void {
120 if (process.env.NODE_ENV === 'development') {
121 if (!getCurrentScope()) {
122 console.warn(
123 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
124 )
125 }
126 }
127​
128 const client = queryClient || useQueryClient()
129​
130 watchEffect(() => {
131 const resolvedOptions = isGetter(options) ? options() : unref(options)
132​
133 const clonedOptions: UsePrefetchInfiniteQueryOptions<
134 TQueryFnData,
135 TError,
136 TData,
137 TQueryKey,
138 TPageParam
139 > = cloneDeepUnref(resolvedOptions)
140​
141 if (!client.getQueryState(clonedOptions.queryKey)) {
142 void client.infiniteQuery(clonedOptions).then(noop).catch(noop)
143 }
144 })