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

usePrefetchInfiniteQuery.ts

156 lines4.8 KB

1import { getCurrentScope, unref, watchEffect } from 'vue-demi'
2import { noop } from '@tanstack/query-core'
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
18 * to `queryClient.infiniteQuery`, 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 *
51 * @param value - The option value.
52 * @returns `true` if `value` is a function.
53 */
54function isGetter<T>(value: MaybeRefOrGetter<T>): value is () => T {
55 return typeof value === 'function'
57​
58/**
59 * `usePrefetchInfiniteQuery` does not return anything β€” it fires a prefetch as
60 * a reactive side effect, useful for kicking off a fetch ahead of the component
61 * that will actually render the data with `useInfiniteQuery`. You can pass
62 * everything to `usePrefetchInfiniteQuery` that you can pass to
63 * `queryClient.infiniteQuery`, though `queryKey`, `initialPageParam`, and
64 * `getNextPageParam` are always required, and `queryFn` is required unless a
65 * default query function has been defined.
66 *
67 * `getNextPageParam` receives both the last page of the infinite list of data
68 * and the full array of all pages, as well as pageParam information, and should
69 * return a single variable that will be passed to your query function as
70 * `context.pageParam`. Return `undefined` or `null` to indicate there is no
71 * next page available.
72 *
73 * The prefetch is skipped if the query already has any cached state β€” including
74 * a `pending`/`error` state left over from a previous attempt β€” so it won't
75 * refetch data that's already there or already in flight. It re-runs whenever a
76 * reactive dependency in `options` (built with `infiniteQueryOptions`, for
77 * example) changes.
78 *
79 * Fire this during render, before a suspense boundary that wraps a component
80 * using `useInfiniteQuery`'s `suspense()` β€” see the
81 * {@link https://tanstack.com/query/latest/docs/framework/vue/guides/suspense | Suspense guide}.
82 *
83 * @example
84 * ```vue
85 * <script setup lang="ts">
86 * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/vue-query'
87 * import Projects from './Projects.vue'
88 *
89 * const projectsOptions = infiniteQueryOptions({
90 * queryKey: ['projects'],
91 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
92 * initialPageParam: 0,
93 * getNextPageParam: (lastPage) => lastPage.nextId,
94 * })
95 *
96 * // Fire the prefetch as soon as this component runs, before `Projects` mounts and calls `useInfiniteQuery`.
97 * usePrefetchInfiniteQuery(projectsOptions)
98 * </script>
99 *
100 * <template>
101 * <Projects />
102 * </template>
103 * ```
104 *
105 * @param options - A `ref`, plain value, or reactive getter resolving to the
106 * {@link UsePrefetchInfiniteQueryOptions} to use β€” everything you can pass to
107 * `queryClient.infiniteQuery`.
108 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
109 * one provided by `VueQueryPlugin` will be used.
110 */
111export function usePrefetchInfiniteQuery<
112 TQueryFnData = unknown,
113 TError = DefaultError,
114 TData = InfiniteData<TQueryFnData>,
115 TQueryKey extends QueryKey = QueryKey,
116 TPageParam = unknown,
117>(
118 options: MaybeRefOrGetter<
119 MaybeRefDeep<
120 UsePrefetchInfiniteQueryOptions<
121 TQueryFnData,
122 TError,
123 TData,
124 TQueryKey,
125 TPageParam
126 >
127 >
128 >,
129 queryClient?: QueryClient,
130): void {
131 if (process.env.NODE_ENV === 'development') {
132 if (!getCurrentScope()) {
133 console.warn(
134 '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.',
135 )
136 }
137 }
138​
139 const client = queryClient || useQueryClient()
140​
141 watchEffect(() => {
142 const resolvedOptions = isGetter(options) ? options() : unref(options)
143​
144 const clonedOptions: UsePrefetchInfiniteQueryOptions<
145 TQueryFnData,
146 TError,
147 TData,
148 TQueryKey,
149 TPageParam
150 > = cloneDeepUnref(resolvedOptions)
151​
152 if (!client.getQueryState(clonedOptions.queryKey)) {
153 void client.infiniteQuery(clonedOptions).then(noop).catch(noop)
154 }
155 })