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

createInfiniteQueryController.ts

428 lines11.3 KB

1import { InfiniteQueryObserver } from '@tanstack/query-core'
2import { createValueAccessor, readAccessor } from './accessor.js'
3import { createMissingQueryClientError } from './context.js'
4import { BaseController } from './controllers/BaseController.js'
5import { QueryObserverResultTracker } from './queryObserverResultTracker.js'
6import type { Accessor, ValueAccessor } from './accessor.js'
7import type {
8 DefaultError,
9 DefaultedInfiniteQueryObserverOptions,
10 InfiniteData,
11 InfiniteQueryObserverOptions,
12 InfiniteQueryObserverResult,
13 QueryClient,
14 QueryKey,
15} from '@tanstack/query-core'
16import type { ReactiveControllerHost } from 'lit'
17​
18/**
19 * Options accepted by `createInfiniteQueryController`.
20 *
21 * This is the Lit adapter shape for `InfiniteQueryObserverOptions`. Pass it
22 * directly or through an `Accessor` when the options depend on Lit host state.
23 */
24export type CreateInfiniteQueryOptions<
25 TQueryFnData = unknown,
26 TError = DefaultError,
27 TData = InfiniteData<TQueryFnData>,
28 TQueryKey extends QueryKey = QueryKey,
29 TPageParam = unknown,
30> = InfiniteQueryObserverOptions<
31 TQueryFnData,
32 TError,
33 TData,
34 TQueryKey,
35 TPageParam
37​
38/**
39 * Accessor returned by `createInfiniteQueryController`.
40 *
41 * Call the accessor or read its `current` property to get the latest infinite
42 * query result. The attached methods delegate to the active infinite query
43 * observer.
44 */
45export type InfiniteQueryResultAccessor<TData, TError> = ValueAccessor<
46 InfiniteQueryObserverResult<TData, TError>
47> & {
48 /** Refetches the current infinite query. */
49 refetch: InfiniteQueryObserverResult<TData, TError>['refetch']
50 /** Fetches the next page for the current infinite query. */
51 fetchNextPage: InfiniteQueryObserverResult<TData, TError>['fetchNextPage']
52 /** Fetches the previous page for the current infinite query. */
53 fetchPreviousPage: InfiniteQueryObserverResult<
54 TData,
55 TError
56 >['fetchPreviousPage']
57 /** Removes the controller from its Lit host and unsubscribes observers. */
58 destroy: () => void
60​
61function createPendingInfiniteQueryResult<
62 TData,
63 TError,
64>(): InfiniteQueryObserverResult<TData, TError> {
65 return {
66 data: undefined,
67 dataUpdatedAt: 0,
68 error: null,
69 errorUpdatedAt: 0,
70 failureCount: 0,
71 failureReason: null,
72 errorUpdateCount: 0,
73 isError: false,
74 isFetched: false,
75 isFetchedAfterMount: false,
76 isFetching: false,
77 isInitialLoading: false,
78 isLoading: false,
79 isLoadingError: false,
80 isPaused: false,
81 isPending: true,
82 isPlaceholderData: false,
83 isRefetchError: false,
84 isRefetching: false,
85 isStale: true,
86 isEnabled: true,
87 isSuccess: false,
88 fetchStatus: 'idle',
89 status: 'pending',
90 refetch: (() =>
91 Promise.reject(
92 createMissingQueryClientError(),
93 )) as InfiniteQueryObserverResult<TData, TError>['refetch'],
94 fetchNextPage: (() =>
95 Promise.reject(
96 createMissingQueryClientError(),
97 )) as InfiniteQueryObserverResult<TData, TError>['fetchNextPage'],
98 fetchPreviousPage: (() =>
99 Promise.reject(
100 createMissingQueryClientError(),
101 )) as InfiniteQueryObserverResult<TData, TError>['fetchPreviousPage'],
102 hasNextPage: false,
103 hasPreviousPage: false,
104 isFetchNextPageError: false,
105 isFetchingNextPage: false,
106 isFetchPreviousPageError: false,
107 isFetchingPreviousPage: false,
108 } as unknown as InfiniteQueryObserverResult<TData, TError>
110​
111class InfiniteQueryController<
112 TQueryFnData,
113 TError,
114 TData,
115 TQueryKey extends QueryKey,
116 TPageParam,
117> extends BaseController<InfiniteQueryObserverResult<TData, TError>> {
118 private readonly options: Accessor<
119 CreateInfiniteQueryOptions<
120 TQueryFnData,
121 TError,
122 TData,
123 TQueryKey,
124 TPageParam
125 >
126 >
127 private observer:
128 | InfiniteQueryObserver<TQueryFnData, TError, TData, TQueryKey, TPageParam>
129 | undefined
130 private readonly resultTracker = new QueryObserverResultTracker<
131 InfiniteQueryObserverResult<TData, TError>
132 >()
133 private unsubscribe: (() => void) | undefined
134 private queryClient: QueryClient | undefined
135​
136 constructor(
137 host: ReactiveControllerHost,
138 options: Accessor<
139 CreateInfiniteQueryOptions<
140 TQueryFnData,
141 TError,
142 TData,
143 TQueryKey,
144 TPageParam
145 >
146 >,
147 queryClient?: QueryClient,
148 ) {
149 super(host, createPendingInfiniteQueryResult(), queryClient)
150 this.options = options
151​
152 if (!queryClient) {
153 return
154 }
155​
156 if (typeof options === 'function') {
157 return
158 }
159​
160 const defaulted = this.defaultOptions(queryClient)
161 const observer = new InfiniteQueryObserver(queryClient, defaulted)
162 this.queryClient = queryClient
163 this.observer = observer
164 this.assignObserverResult(observer.getOptimisticResult(defaulted))
165 }
166​
167 protected onConnected(): void {
168 if (!this.syncClient()) {
169 return
170 }
171​
172 this.refreshOptions()
173 this.subscribe()
174 this.observer?.updateResult()
175 if (this.observer) {
176 this.setObserverResult(this.observer.getCurrentResult())
177 }
178 }
179​
180 protected onDisconnected(): void {
181 this.unsubscribeObserver()
182 this.syncClient()
183 }
184​
185 protected onHostUpdate(): void {
186 if (typeof this.options !== 'function') {
187 return
188 }
189​
190 this.refreshOptions()
191 }
192​
193 protected onQueryClientChanged(): void {
194 if (!this.syncClient() || !this.connectedState) {
195 return
196 }
197​
198 this.refreshOptions()
199 this.subscribe()
200 this.observer?.updateResult()
201 if (this.observer) {
202 this.setObserverResult(this.observer.getCurrentResult())
203 }
204 }
205​
206 refetch: InfiniteQueryObserverResult<TData, TError>['refetch'] = (
207 ...args
208 ) => {
209 if (!this.applyOptions() || !this.observer) {
210 return Promise.reject(createMissingQueryClientError())
211 }
212​
213 return this.observer.refetch(...args)
214 }
215​
216 fetchNextPage: InfiniteQueryObserverResult<TData, TError>['fetchNextPage'] = (
217 ...args
218 ) => {
219 if (!this.applyOptions() || !this.observer) {
220 return Promise.reject(createMissingQueryClientError())
221 }
222​
223 return this.observer.fetchNextPage(...args)
224 }
225​
226 fetchPreviousPage: InfiniteQueryObserverResult<
227 TData,
228 TError
229 >['fetchPreviousPage'] = (...args) => {
230 if (!this.applyOptions() || !this.observer) {
231 return Promise.reject(createMissingQueryClientError())
232 }
233​
234 return this.observer.fetchPreviousPage(...args)
235 }
236​
237 readCurrent(): InfiniteQueryObserverResult<TData, TError> {
238 if (this.observer) {
239 this.assignObserverResult(this.observer.getCurrentResult())
240 }
241​
242 return this.current
243 }
244​
245 private subscribe(): void {
246 if (!this.observer) {
247 return
248 }
249​
250 if (this.unsubscribe) {
251 return
252 }
253​
254 this.unsubscribe = this.observer.subscribe((next) => {
255 this.setObserverResult(next)
256 })
257 }
258​
259 private unsubscribeObserver(): void {
260 this.unsubscribe?.()
261 this.unsubscribe = undefined
262 }
263​
264 private syncClient(): boolean {
265 const nextClient = this.tryGetQueryClient()
266 if (!nextClient) {
267 this.unsubscribeObserver()
268 this.queryClient = undefined
269 this.observer = undefined
270 this.resultTracker.reset()
271 this.setResult(createPendingInfiniteQueryResult())
272 return false
273 }
274​
275 if (nextClient === this.queryClient) {
276 return true
277 }
278​
279 this.unsubscribeObserver()
280 this.queryClient = nextClient
281 const options = this.defaultOptions(this.queryClient)
282 this.observer = new InfiniteQueryObserver(this.queryClient, options)
283 this.setObserverResult(this.observer.getOptimisticResult(options))
284 return true
285 }
286​
287 private applyOptions(): boolean {
288 if (!this.syncClient() || !this.observer || !this.queryClient) {
289 return false
290 }
291​
292 const options = this.defaultOptions(this.queryClient)
293 this.observer.setOptions(options)
294 return true
295 }
296​
297 private refreshOptions(): boolean {
298 if (!this.applyOptions() || !this.observer) {
299 return false
300 }
301​
302 this.setObserverResult(this.observer.getCurrentResult())
303 return true
304 }
305​
306 private assignObserverResult(
307 result: InfiniteQueryObserverResult<TData, TError>,
308 ): void {
309 const trackedResult = this.resultTracker.update(this.observer, result)
310 if (trackedResult) {
311 this.result = trackedResult
312 }
313 }
314​
315 private setObserverResult(
316 result: InfiniteQueryObserverResult<TData, TError>,
317 ): void {
318 const trackedResult = this.resultTracker.update(this.observer, result)
319 if (trackedResult) {
320 this.setResult(trackedResult)
321 }
322 }
323​
324 private defaultOptions(
325 client = this.queryClient,
326 ): DefaultedInfiniteQueryObserverOptions<
327 TQueryFnData,
328 TError,
329 TData,
330 TQueryKey,
331 TPageParam
332 > {
333 if (!client) {
334 throw createMissingQueryClientError()
335 }
336​
337 const defaulted = client.defaultQueryOptions(
338 readAccessor(this.options),
339 ) as DefaultedInfiniteQueryObserverOptions<
340 TQueryFnData,
341 TError,
342 TData,
343 TQueryKey,
344 TPageParam
345 >
346 ;(defaulted as { _optimisticResults?: 'optimistic' })._optimisticResults =
347 'optimistic'
348 return defaulted
349 }
351​
352/**
353 * Creates a Lit reactive controller that subscribes the host to an infinite
354 * query.
355 *
356 * The returned accessor is callable and also exposes `current`, `refetch`,
357 * `fetchNextPage`, `fetchPreviousPage`, and `destroy`. When `options` is a
358 * function, it is re-read during host updates so query keys and options can
359 * follow reactive host state.
360 *
361 * If `queryClient` is omitted, the controller resolves the client from the
362 * nearest connected `QueryClientProvider`.
363 *
364 * @param host - The Lit reactive controller host that owns the infinite query
365 * subscription.
366 * @param options - Infinite query observer options, or a getter that returns
367 * options.
368 * @param queryClient - Optional explicit query client. Provide this for
369 * controllers that should not resolve a client from Lit context.
370 * @returns An accessor for the latest infinite query result with page helper
371 * methods.
372 *
373 * @example
374 * ```ts
375 * import { LitElement, html } from 'lit'
376 * import { createInfiniteQueryController } from '@tanstack/lit-query'
377 *
378 * class ProjectsView extends LitElement {
379 * private readonly projects = createInfiniteQueryController(this, {
380 * queryKey: ['projects'],
381 * queryFn: ({ pageParam }) => fetchProjects(pageParam),
382 * initialPageParam: 0,
383 * getNextPageParam: (lastPage) => lastPage.nextCursor,
384 * })
385 *
386 * render() {
387 * const query = this.projects()
388 *
389 * return html`
390 * <button ?disabled=${!query.hasNextPage} @click=${() => this.projects.fetchNextPage()}>
391 * Load more
392 * </button>
393 * `
394 * }
395 * }
396 * ```
397 */
398export function createInfiniteQueryController<
399 TQueryFnData = unknown,
400 TError = DefaultError,
401 TData = InfiniteData<TQueryFnData>,
402 TQueryKey extends QueryKey = QueryKey,
403 TPageParam = unknown,
404>(
405 host: ReactiveControllerHost,
406 options: Accessor<
407 CreateInfiniteQueryOptions<
408 TQueryFnData,
409 TError,
410 TData,
411 TQueryKey,
412 TPageParam
413 >
414 >,
415 queryClient?: QueryClient,
416): InfiniteQueryResultAccessor<TData, TError> {
417 const controller = new InfiniteQueryController(host, options, queryClient)
418​
419 return Object.assign(
420 createValueAccessor(() => controller.readCurrent()),
421 {
422 refetch: controller.refetch,
423 fetchNextPage: controller.fetchNextPage,
424 fetchPreviousPage: controller.fetchPreviousPage,
425 destroy: () => controller.destroy(),
426 },
427 )