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