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

QueryObserver.md

594 lines14.5 KB

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`