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