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