Open History to see the last commit
1import { InfiniteQueryObserver } from '@tanstack/query-core'
2import { createMemo } from 'solid-js'
3import { useBaseQueryLayer } from './useBaseQuery'
4import type {
5 DefaultError,
6 FetchNextPageOptions,
7 FetchPreviousPageOptions,
8 InfiniteData,
9 InfiniteQueryObserverResult,
10 QueryKey,
11 QueryObserver,
12} from '@tanstack/query-core'
13import type { QueryClient } from './QueryClient'
14import type {
15 DefinedUseInfiniteQueryResult,
16 UseInfiniteQueryOptions,
17 UseInfiniteQueryResult,
18} from './types'
19import type { Accessor } from 'solid-js'
20import type {
21 DefinedInitialDataInfiniteOptions,
22 UndefinedInitialDataInfiniteOptions,
23} from './infiniteQueryOptions'
24β
25/**
26 * Page-boundary checks, mirrored from query-core's `infiniteQueryBehavior`
27 * (they are module-private there β not exported through the package index).
28 * Pure functions of options + cached data; keep byte-compatible with core.
29 */
30interface PageParamsOptions {
31 getNextPageParam: (
32 lastPage: unknown,
33 pages: Array<unknown>,
34 lastPageParam: unknown,
35 pageParams: Array<unknown>,
36 ) => unknown
37 getPreviousPageParam?: (
38 firstPage: unknown,
39 pages: Array<unknown>,
40 firstPageParam: unknown,
41 pageParams: Array<unknown>,
42 ) => unknown
43}
44β
45/**
46 * Checks whether `getNextPageParam` yields a param for the page after the last cached one.
47 * @param options - The options holding `getNextPageParam`.
48 * @param data - The cached infinite data, if any.
49 * @returns `true` if there is a next page to fetch.
50 */
51function hasNextPage(
52 options: PageParamsOptions,
53 data?: InfiniteData<unknown>,
54): boolean {
55 if (!data || data.pages.length === 0) return false
56 const lastIndex = data.pages.length - 1
57 return (
58 options.getNextPageParam(
59 data.pages[lastIndex],
60 data.pages,
61 data.pageParams[lastIndex],
62 data.pageParams,
63 ) != null
64 )
65}
66β
67/**
68 * Checks whether `getPreviousPageParam` yields a param for the page before the first cached one.
69 * @param options - The options holding `getPreviousPageParam`.
70 * @param data - The cached infinite data, if any.
71 * @returns `true` if there is a previous page to fetch.
72 */
73function hasPreviousPage(
74 options: PageParamsOptions,
75 data?: InfiniteData<unknown>,
76): boolean {
77 if (!data || data.pages.length === 0 || !options.getPreviousPageParam)
78 return false
79 return (
80 options.getPreviousPageParam(
81 data.pages[0],
82 data.pages,
83 data.pageParams[0],
84 data.pageParams,
85 ) != null
86 )
87}
88β
89export function useInfiniteQuery<
90 TQueryFnData,
91 TError = DefaultError,
92 TData = InfiniteData<TQueryFnData>,
93 TQueryKey extends QueryKey = QueryKey,
94 TPageParam = unknown,
95>(
96 options: DefinedInitialDataInfiniteOptions<
97 TQueryFnData,
98 TError,
99 TData,
100 TQueryKey,
101 TPageParam
102 >,
103 queryClient?: Accessor<QueryClient>,
104): DefinedUseInfiniteQueryResult<TData, TError>
105β
106/**
107 * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
108 * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
109 * @param options - An accessor returning the {@link UndefinedInitialDataInfiniteOptions} to use β everything
110 * you can pass to `useInfiniteQuery`.
111 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
112 * will be used.
113 * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
114 * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
115 * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
116 * `InfiniteData<TQueryFnData>` shape.
117 * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
118 * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
119 * actions, or add conditions like `hasNextPage && !isFetching`.
120 * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
121 * @example
122 * Fetching the next page from a "Load More" button click:
123 * ```tsx
124 * import { For, Match, Switch } from 'solid-js'
125 * import { useInfiniteQuery } from '@tanstack/solid-query'
126 *
127 * function Projects() {
128 * const projectsQuery = useInfiniteQuery(() => ({
129 * queryKey: ['projects'],
130 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
131 * initialPageParam: 0,
132 * getNextPageParam: (lastPage) => lastPage.nextId,
133 * }))
134 *
135 * return (
136 * <Switch>
137 * <Match when={projectsQuery.isPending}>Loading...</Match>
138 * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
139 * <Match when={projectsQuery.isSuccess}>
140 * <ul>
141 * <For each={projectsQuery.data.pages}>
142 * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
143 * </For>
144 * </ul>
145 * <button
146 * onClick={() => projectsQuery.fetchNextPage()}
147 * disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
148 * >
149 * {projectsQuery.isFetchingNextPage
150 * ? 'Loading more...'
151 * : projectsQuery.hasNextPage
152 * ? 'Load More'
153 * : 'Nothing more to load'}
154 * </button>
155 * </Match>
156 * </Switch>
157 * )
158 * }
159 * ```
160 * @example
161 * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
162 * sentinel element after the list:
163 * ```tsx
164 * import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
165 * import { useInfiniteQuery } from '@tanstack/solid-query'
166 *
167 * function Projects() {
168 * const projectsQuery = useInfiniteQuery(() => ({
169 * queryKey: ['projects'],
170 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
171 * initialPageParam: 0,
172 * getNextPageParam: (lastPage) => lastPage.nextId,
173 * }))
174 *
175 * let sentinelRef: HTMLDivElement | undefined
176 *
177 * createEffect(() => {
178 * if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
179 *
180 * const observer = new IntersectionObserver(([entry]) => {
181 * if (entry?.isIntersecting) projectsQuery.fetchNextPage()
182 * })
183 * observer.observe(sentinelRef)
184 *
185 * onCleanup(() => observer.disconnect())
186 * })
187 *
188 * return (
189 * <Switch>
190 * <Match when={projectsQuery.isPending}>Loading...</Match>
191 * <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
192 * <Match when={projectsQuery.isSuccess}>
193 * <ul>
194 * <For each={projectsQuery.data.pages}>
195 * {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
196 * </For>
197 * </ul>
198 * <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
199 * </Match>
200 * </Switch>
201 * )
202 * }
203 * ```
204 */
205export function useInfiniteQuery<
206 TQueryFnData,
207 TError = DefaultError,
208 TData = InfiniteData<TQueryFnData>,
209 TQueryKey extends QueryKey = QueryKey,
210 TPageParam = unknown,
211>(
212 options: UndefinedInitialDataInfiniteOptions<
213 TQueryFnData,
214 TError,
215 TData,
216 TQueryKey,
217 TPageParam
218 >,
219 queryClient?: Accessor<QueryClient>,
220): UseInfiniteQueryResult<TData, TError>
221β
222export function useInfiniteQuery<
223 TQueryFnData,
224 TError = DefaultError,
225 TData = InfiniteData<TQueryFnData>,
226 TQueryKey extends QueryKey = QueryKey,
227 TPageParam = unknown,
228>(
229 options: UseInfiniteQueryOptions<
230 TQueryFnData,
231 TError,
232 TData,
233 TQueryKey,
234 TPageParam
235 >,
236 queryClient?: Accessor<QueryClient>,
237): UseInfiniteQueryResult<TData, TError> {
238 /**
239 * Pagers ride the same entry as every other read: the base layer owns
240 * the data node, meta projection, and lifecycle observer (an
241 * `InfiniteQueryObserver`, so mount policy and refetches use the
242 * infinite behavior). This layer adds the page surface on top.
243 */
244 const layer = useBaseQueryLayer(
245 // `_type` is how query-core stamps a cache entry as infinite
246 // (`Query.setOptions` β `#queryType`), which makes every fetch attach
247 // `infiniteQueryBehavior`. Core only sets it inside
248 // `InfiniteQueryObserver.setOptions`, but the adapter's pull path can
249 // build and fetch the entry first (reactive key change recomputes the
250 // data memo before the deferred observer effect runs) β without the
251 // stamp that fetch would run as a plain query and corrupt the entry.
252 createMemo(() => ({ ...options(), _type: 'infinite' }) as any),
253 InfiniteQueryObserver as typeof QueryObserver,
254 queryClient,
255 )
256 const observer = layer.observer as unknown as InfiniteQueryObserver<
257 TQueryFnData,
258 TError,
259 TData,
260 TQueryKey,
261 TPageParam
262 >
263β
264 /**
265 * Committed fetch direction β set when a page fetch dispatches,
266 * version-tracked through the layer's query accessor.
267 * @returns `'forward'` or `'backward'` for a page fetch, `undefined` otherwise.
268 */
269 const direction = () =>
270 (layer.query().state.fetchMeta as any)?.fetchMore?.direction
271β
272 const pageOptions = () =>
273 layer.defaultedOptions() as unknown as PageParamsOptions
274 const infiniteData = () =>
275 layer.query().state.data as InfiniteData<unknown> | undefined
276β
277 // Read `direction()` before `isFetching()` to work around solidjs/solid#4966.
278 const isFetchingPage = (expected: 'forward' | 'backward') => {
279 const current = direction()
280 return layer.isFetching() && current === expected
281 }
282 const isFetchingNextPage = () => isFetchingPage('forward')
283 const isFetchingPreviousPage = () => isFetchingPage('backward')
284 const isError = () => layer.status() === 'error'
285β
286 // The base result's getters transfer as-is; the infinite surface layers
287 // over them, and isRefetching/isRefetchError narrow to exclude page
288 // fetches (matching core's InfiniteQueryObserver result shape).
289 const result = Object.defineProperties(
290 {},
291 {
292 ...Object.getOwnPropertyDescriptors(layer.result),
293 fetchNextPage: {
294 value: (fetchOptions?: FetchNextPageOptions) =>
295 observer.fetchNextPage(fetchOptions),
296 enumerable: true,
297 },
298 fetchPreviousPage: {
299 value: (fetchOptions?: FetchPreviousPageOptions) =>
300 observer.fetchPreviousPage(fetchOptions),
301 enumerable: true,
302 },
303 hasNextPage: {
304 get: () => hasNextPage(pageOptions(), infiniteData()),
305 enumerable: true,
306 },
307 hasPreviousPage: {
308 get: () => hasPreviousPage(pageOptions(), infiniteData()),
309 enumerable: true,
310 },
311 isFetchingNextPage: {
312 get: isFetchingNextPage,
313 enumerable: true,
314 },
315 isFetchingPreviousPage: {
316 get: isFetchingPreviousPage,
317 enumerable: true,
318 },
319 isFetchNextPageError: {
320 get: () => isError() && direction() === 'forward',
321 enumerable: true,
322 },
323 isFetchPreviousPageError: {
324 get: () => isError() && direction() === 'backward',
325 enumerable: true,
326 },
327 isRefetching: {
328 get: () => {
329 const current = direction()
330 return (
331 layer.isFetching() &&
332 layer.status() !== 'pending' &&
333 current !== 'forward' &&
334 current !== 'backward'
335 )
336 },
337 enumerable: true,
338 },
339 isRefetchError: {
340 get: () => {
341 const errored = isError() && layer.query().state.dataUpdatedAt !== 0
342 return errored && direction() === undefined
343 },
344 enumerable: true,
345 },
346 },
347 ) as InfiniteQueryObserverResult<TData, TError>
348β
349 return result as unknown as UseInfiniteQueryResult<TData, TError>
350}