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

QueryObserver.md

591 lines14.3 KB

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`
73​
74##### options
75​
76`QueryObserverOptions`\<`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`\<`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`\<`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`