Open History to see the last commit
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`