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