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