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

QueryObserver.md

593 lines14.6 KB

1---
2id: QueryObserver
3title: QueryObserver
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8Defined in: [packages/query-core/src/queryObserver.ts:56](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L56)
9​
10A `QueryObserver` watches a single query in the `QueryCache` and computes a
11`QueryObserverResult` from its state, recomputing and notifying subscribers
12whenever the underlying query (or the observer's options) changes. It is
13the primitive that framework adapters (e.g. `useQuery`) build their hooks
14on top of, but it can also be used directly to observe and switch between
15queries outside of any framework.
16​
17## Example
18​
19```ts
20const observer = new QueryObserver(queryClient, {
21 queryKey: ['posts'],
22 queryFn: fetchPosts,
23})
24​
25const unsubscribe = observer.subscribe((result) => {
26 console.log(result.data)
27})
28```
29​
30## Extends
31​
32- `Subscribable`\<`QueryObserverListener`\<`TData`, `TError`\>\>
33​
34## Extended by
35​
36- [`InfiniteQueryObserver`](InfiniteQueryObserver.md)
37​
38## Type Parameters
39​
40### TQueryFnData
41​
42`TQueryFnData` = `unknown`
43​
44### TError
45​
46`TError` = [`DefaultError`](../type-aliases/DefaultError.md)
47​
48### TData
49​
50`TData` = `TQueryFnData`
51​
52### TQueryData
53​
54`TQueryData` = `TQueryFnData`
55​
56### TQueryKey
57​
58`TQueryKey` *extends* [`QueryKey`](../type-aliases/QueryKey.md) = [`QueryKey`](../type-aliases/QueryKey.md)
59​
60## Constructors
61​
62### Constructor
63​
64```ts
65new QueryObserver<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends readonly unknown[] = readonly unknown[]>(client: QueryClient, options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
66```
67​
68Defined in: [packages/query-core/src/queryObserver.ts:86](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L86)
69​
70#### Parameters
71​
72##### client
73​
74[`QueryClient`](QueryClient.md)
75​
76##### options
77​
78[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
79​
80#### Returns
81​
82`QueryObserver`\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
83​
84#### Overrides
85​
86```ts
87Subscribable<QueryObserverListener<TData, TError>>.constructor
88```
89​
90## Properties
91​
92### options
93​
94```ts
95options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
96```
97​
98Defined in: [packages/query-core/src/queryObserver.ts:88](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L88)
99​
100## Methods
101​
102### destroy()
103​
104```ts
105destroy(): void;
106```
107​
108Defined in: [packages/query-core/src/queryObserver.ts:166](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L166)
109​
110Stops observing the current query: clears all listeners, cancels the
111stale and refetch-interval timers, and removes this observer from the
112query it was observing.
113​
114#### Returns
115​
116`void`
117​
118***
119​
120### fetchOptimistic()
121​
122```ts
123fetchOptimistic(options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): Promise<QueryObserverResult<TData, TError>>;
124```
125​
126Defined in: [packages/query-core/src/queryObserver.ts:412](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L412)
127​
128Fetches a query defined by the given options without affecting this
129observer's own tracked query or result, and returns a promise that
130resolves with the `QueryObserverResult` for that fetch. This is useful
131for prefetching data that another observer (e.g. a query about to be
132navigated to) will need, ahead of time.
133​
134#### Parameters
135​
136##### options
137​
138[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
139​
140The observer options of the query to fetch.
141​
142#### Returns
143​
144`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
145​
146A promise that resolves with the result for the fetched query.
147​
148#### Example
149​
150```ts
151const result = await observer.fetchOptimistic({
152 queryKey: ['posts', 2],
153 queryFn: () => fetchPost(2),
154})
155console.log(result.data)
156```
157​
158***
159​
160### getCurrentQuery()
161​
162```ts
163getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey>;
164```
165​
166Defined in: [packages/query-core/src/queryObserver.ts:371](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L371)
167​
168Returns the `Query` instance this observer is currently observing.
169​
170#### Returns
171​
172[`Query`](Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>
173​
174The observed query.
175​
176***
177​
178### getCurrentResult()
179​
180```ts
181getCurrentResult(): QueryObserverResult<TData, TError>;
182```
183​
184Defined in: [packages/query-core/src/queryObserver.ts:330](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L330)
185​
186Returns the most recently computed `QueryObserverResult` for the
187observed query. This is a point-in-time read; to be notified of updates
188as they happen, subscribe to the observer instead (its inherited
189`subscribe` method).
190​
191#### Returns
192​
193[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
194​
195The observer's latest result.
196​
197#### Example
198​
199```ts
200const result = observer.getCurrentResult()
201console.log(result.status, result.data)
202```
203​
204***
205​
206### getOptimisticResult()
207​
208```ts
209getOptimisticResult(options: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverResult<TData, TError>;
210```
211​
212Defined in: [packages/query-core/src/queryObserver.ts:281](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L281)
213​
214Computes the result the observer would produce for the given (already-defaulted) options
215right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
216subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
217returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
218​
219#### Parameters
220​
221##### options
222​
223[`DefaultedQueryObserverOptions`](../type-aliases/DefaultedQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
224​
225The defaulted observer options to compute the result for.
226​
227#### Returns
228​
229[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
230​
231The result for the given options.
232​
233***
234​
235### hasListeners()
236​
237```ts
238hasListeners(): boolean;
239```
240​
241Defined in: [packages/query-core/src/subscribable.ts:43](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L43)
242​
243Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
244​
245#### Returns
246​
247`boolean`
248​
249`true` if at least one listener is registered.
250​
251#### Inherited from
252​
253```ts
254Subscribable.hasListeners
255```
256​
257***
258​
259### refetch()
260​
261```ts
262refetch(options?: RefetchOptions): Promise<QueryObserverResult<TData, TError>>;
263```
264​
265Defined in: [packages/query-core/src/queryObserver.ts:387](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L387)
266​
267Refetches the observed query and returns a promise that resolves with
268the resulting `QueryObserverResult`.
269​
270#### Parameters
271​
272##### options?
273​
274[`RefetchOptions`](../interfaces/RefetchOptions.md) = `{}`
275​
276Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
277it, and `throwOnError` to `true` to reject when the refetch fails.
278​
279#### Returns
280​
281`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
282​
283A promise that resolves with the result after the refetch.
284​
285#### Example
286​
287```ts
288const result = await observer.refetch({ cancelRefetch: false })
289console.log(result.data)
290```
291​
292***
293​
294### setOptions()
295​
296```ts
297setOptions(options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): void;
298```
299​
300Defined in: [packages/query-core/src/queryObserver.ts:189](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L189)
301​
302Updates the observer's options. This will re-resolve the query being
303observed (switching to a different query if the `queryKey` changed),
304trigger a fetch if the new options require one and the observer has
305subscribers, recompute the current result, and reschedule the stale and
306refetch-interval timers as needed.
307​
308#### Parameters
309​
310##### options
311​
312[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
313​
314The new observer options. They are defaulted with [QueryClient#defaultQueryOptions](QueryClient.md#defaultqueryoptions) before being applied.
315​
316#### Returns
317​
318`void`
319​
320#### Throws
321​
322If `enabled` is neither a boolean nor a function.
323​
324#### Example
325​
326```ts
327observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
328// later: switch to a different query, reusing the same observer
329observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
330```
331​
332***
333​
334### shouldFetchOnReconnect()
335​
336```ts
337shouldFetchOnReconnect(): boolean;
338```
339​
340Defined in: [packages/query-core/src/queryObserver.ts:139](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L139)
341​
342Returns whether the observed query is currently stale and configured
343(via the `refetchOnReconnect` option) to refetch when the network
344reconnects.
345​
346#### Returns
347​
348`boolean`
349​
350`true` if the observer should refetch the query on reconnect.
351​
352***
353​
354### shouldFetchOnWindowFocus()
355​
356```ts
357shouldFetchOnWindowFocus(): boolean;
358```
359​
360Defined in: [packages/query-core/src/queryObserver.ts:153](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L153)
361​
362Returns whether the observed query is currently stale and configured
363(via the `refetchOnWindowFocus` option) to refetch when the window
364regains focus.
365​
366#### Returns
367​
368`boolean`
369​
370`true` if the observer should refetch the query on window focus.
371​
372***
373​
374### subscribe()
375​
376```ts
377subscribe(listener: QueryObserverListener): () => void;
378```
379​
380Defined in: [packages/query-core/src/subscribable.ts:28](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L28)
381​
382Registers a listener to be called on every update this object notifies about. Returns a function
383that removes the listener again β€” call it to stop listening. The base class never drops a listener
384on its own, though some subclasses clear all of theirs in `destroy()`.
385​
386#### Parameters
387​
388##### listener
389​
390`QueryObserverListener`
391​
392Called on each update, with whatever the subclass passes to its subscribers.
393​
394#### Returns
395​
396A function that removes the listener.
397​
398() => `void`
399​
400#### Example
401​
402```ts
403const unsubscribe = subscribable.subscribe(() => {
404 // react to the update
405})
406​
407unsubscribe()
408```
409​
410#### Inherited from
411​
412```ts
413Subscribable.subscribe
414```
415​
416***
417​
418### trackProp()
419​
420```ts
421trackProp(key:
422 | "error"
423 | "data"
424 | "isError"
425 | "isPending"
426 | "isLoading"
427 | "isLoadingError"
428 | "isRefetchError"
429 | "isSuccess"
430 | "isPlaceholderData"
431 | "status"
432 | "dataUpdatedAt"
433 | "errorUpdatedAt"
434 | "failureCount"
435 | "failureReason"
436 | "errorUpdateCount"
437 | "isFetched"
438 | "isFetchedAfterMount"
439 | "isFetching"
440 | "isInitialLoading"
441 | "isPaused"
442 | "isRefetching"
443 | "isStale"
444 | "isEnabled"
445 | "refetch"
446 | "fetchStatus"): void;
447```
448​
449Defined in: [packages/query-core/src/queryObserver.ts:363](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L363)
450​
451Records that the given `QueryObserverResult` property was read, so a subsequent update only
452notifies this observer if a tracked property actually changed. Normally called indirectly via
453[QueryObserver#trackResult](#trackresult)'s proxy; exposed directly for adapters that track property
454access themselves (e.g. through their own reactivity system) instead of via the proxy.
455​
456#### Parameters
457​
458##### key
459​
460 \| `"error"`
461 \| `"data"`
462 \| `"isError"`
463 \| `"isPending"`
464 \| `"isLoading"`
465 \| `"isLoadingError"`
466 \| `"isRefetchError"`
467 \| `"isSuccess"`
468 \| `"isPlaceholderData"`
469 \| `"status"`
470 \| `"dataUpdatedAt"`
471 \| `"errorUpdatedAt"`
472 \| `"failureCount"`
473 \| `"failureReason"`
474 \| `"errorUpdateCount"`
475 \| `"isFetched"`
476 \| `"isFetchedAfterMount"`
477 \| `"isFetching"`
478 \| `"isInitialLoading"`
479 \| `"isPaused"`
480 \| `"isRefetching"`
481 \| `"isStale"`
482 \| `"isEnabled"`
483 \| `"refetch"`
484 \| `"fetchStatus"`
485​
486The name of the property that was read.
487​
488#### Returns
489​
490`void`
491​
492***
493​
494### trackResult()
495​
496```ts
497trackResult(result: QueryObserverResult<TData, TError>, onPropTracked?: (key:
498 | "error"
499 | "data"
500 | "isError"
501 | "isPending"
502 | "isLoading"
503 | "isLoadingError"
504 | "isRefetchError"
505 | "isSuccess"
506 | "isPlaceholderData"
507 | "status"
508 | "dataUpdatedAt"
509 | "errorUpdatedAt"
510 | "failureCount"
511 | "failureReason"
512 | "errorUpdateCount"
513 | "isFetched"
514 | "isFetchedAfterMount"
515 | "isFetching"
516 | "isInitialLoading"
517 | "isPaused"
518 | "isRefetching"
519 | "isStale"
520 | "isEnabled"
521 | "refetch"
522| "fetchStatus") => void): QueryObserverResult<TData, TError>;
523```
524​
525Defined in: [packages/query-core/src/queryObserver.ts:343](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L343)
526​
527Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
528[QueryObserver#trackProp](#trackprop) (and an optional `onPropTracked` callback). Used by framework
529adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
530properties you actually read" behavior.
531​
532#### Parameters
533​
534##### result
535​
536[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
537​
538The result to wrap.
539​
540##### onPropTracked?
541​
542(`key`:
543 \| `"error"`
544 \| `"data"`
545 \| `"isError"`
546 \| `"isPending"`
547 \| `"isLoading"`
548 \| `"isLoadingError"`
549 \| `"isRefetchError"`
550 \| `"isSuccess"`
551 \| `"isPlaceholderData"`
552 \| `"status"`
553 \| `"dataUpdatedAt"`
554 \| `"errorUpdatedAt"`
555 \| `"failureCount"`
556 \| `"failureReason"`
557 \| `"errorUpdateCount"`
558 \| `"isFetched"`
559 \| `"isFetchedAfterMount"`
560 \| `"isFetching"`
561 \| `"isInitialLoading"`
562 \| `"isPaused"`
563 \| `"isRefetching"`
564 \| `"isStale"`
565 \| `"isEnabled"`
566 \| `"refetch"`
567 \| `"fetchStatus"`) => `void`
568​
569Called with the name of each property that is read.
570​
571#### Returns
572​
573[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
574​
575A proxy of `result` that tracks property reads.
576​
577***
578​
579### updateResult()
580​
581```ts
582updateResult(): void;
583```
584​
585Defined in: [packages/query-core/src/queryObserver.ts:765](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L765)
586​
587Recomputes and stores the current result from the current query/options, notifying listeners
588if it changed. Framework adapters call this right after subscribing to make sure no query
589update was missed in the gap between creating the observer and subscribing to it.
590​
591#### Returns
592​
593`void`