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