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