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

QueryObserver.md

596 lines14.6 KB

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`