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

QueryObserver.md

534 lines13.3 KB

1---
2id: QueryObserver
3title: QueryObserver
4---
5​
6Defined in: [packages/query-core/src/queryObserver.ts:57](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L57)
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:87](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L87)
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:89](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L89)
97​
98## Methods
99​
100### destroy()
101​
102```ts
103destroy(): void;
104```
105​
106Defined in: [packages/query-core/src/queryObserver.ts:161](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L161)
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:395](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L395)
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​
138#### Returns
139​
140`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
141​
142#### Example
143​
144```ts
145const result = await observer.fetchOptimistic({
146 queryKey: ['posts', 2],
147 queryFn: () => fetchPost(2),
148})
149console.log(result.data)
150```
151​
152***
153​
154### getCurrentQuery()
155​
156```ts
157getCurrentQuery(): Query<TQueryFnData, TError, TQueryData, TQueryKey>;
158```
159​
160Defined in: [packages/query-core/src/queryObserver.ts:357](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L357)
161​
162Returns the `Query` instance this observer is currently observing.
163​
164#### Returns
165​
166[`Query`](Query.md)\<`TQueryFnData`, `TError`, `TQueryData`, `TQueryKey`\>
167​
168***
169​
170### getCurrentResult()
171​
172```ts
173getCurrentResult(): QueryObserverResult<TData, TError>;
174```
175​
176Defined in: [packages/query-core/src/queryObserver.ts:321](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L321)
177​
178Returns the most recently computed `QueryObserverResult` for the
179observed query. This is a point-in-time read; to be notified of updates
180as they happen, subscribe to the observer instead (its inherited
181`subscribe` method).
182​
183#### Returns
184​
185[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
186​
187#### Example
188​
189```ts
190const result = observer.getCurrentResult()
191console.log(result.status, result.data)
192```
193​
194***
195​
196### getOptimisticResult()
197​
198```ts
199getOptimisticResult(options: DefaultedQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserverResult<TData, TError>;
200```
201​
202Defined in: [packages/query-core/src/queryObserver.ts:272](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L272)
203​
204Computes the result the observer would produce for the given (already-defaulted) options
205right now, building the underlying `Query` if it doesn't exist yet, without waiting for a
206subscription callback. Called by framework adapters on every render (e.g. `useQuery`) so the
207returned value is available synchronously, ahead of `setOptions` triggering an actual fetch.
208​
209#### Parameters
210​
211##### options
212​
213[`DefaultedQueryObserverOptions`](../type-aliases/DefaultedQueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
214​
215#### Returns
216​
217[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
218​
219***
220​
221### hasListeners()
222​
223```ts
224hasListeners(): boolean;
225```
226​
227Defined in: [packages/query-core/src/subscribable.ts:41](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L41)
228​
229Returns `true` while at least one listener is registered, `false` once they have all unsubscribed.
230​
231#### Returns
232​
233`boolean`
234​
235#### Inherited from
236​
237```ts
238Subscribable.hasListeners
239```
240​
241***
242​
243### refetch()
244​
245```ts
246refetch(__namedParameters: RefetchOptions): Promise<QueryObserverResult<TData, TError>>;
247```
248​
249Defined in: [packages/query-core/src/queryObserver.ts:371](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L371)
250​
251Refetches the observed query and returns a promise that resolves with
252the resulting `QueryObserverResult`.
253​
254#### Parameters
255​
256##### \_\_namedParameters
257​
258[`RefetchOptions`](../interfaces/RefetchOptions.md) = `{}`
259​
260#### Returns
261​
262`Promise`\<[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>\>
263​
264#### Example
265​
266```ts
267const result = await observer.refetch({ cancelRefetch: false })
268console.log(result.data)
269```
270​
271***
272​
273### setOptions()
274​
275```ts
276setOptions(options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): void;
277```
278​
279Defined in: [packages/query-core/src/queryObserver.ts:182](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L182)
280​
281Updates the observer's options. This will re-resolve the query being
282observed (switching to a different query if the `queryKey` changed),
283trigger a fetch if the new options require one and the observer has
284subscribers, recompute the current result, and reschedule the stale and
285refetch-interval timers as needed.
286​
287#### Parameters
288​
289##### options
290​
291[`QueryObserverOptions`](../interfaces/QueryObserverOptions.md)\<`TQueryFnData`, `TError`, `TData`, `TQueryData`, `TQueryKey`\>
292​
293#### Returns
294​
295`void`
296​
297#### Example
298​
299```ts
300observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) })
301// later: switch to a different query, reusing the same observer
302observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) })
303```
304​
305***
306​
307### shouldFetchOnReconnect()
308​
309```ts
310shouldFetchOnReconnect(): boolean;
311```
312​
313Defined in: [packages/query-core/src/queryObserver.ts:135](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L135)
314​
315Returns whether the observed query is currently stale and configured
316(via the `refetchOnReconnect` option) to refetch when the network
317reconnects.
318​
319#### Returns
320​
321`boolean`
322​
323***
324​
325### shouldFetchOnWindowFocus()
326​
327```ts
328shouldFetchOnWindowFocus(): boolean;
329```
330​
331Defined in: [packages/query-core/src/queryObserver.ts:148](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L148)
332​
333Returns whether the observed query is currently stale and configured
334(via the `refetchOnWindowFocus` option) to refetch when the window
335regains focus.
336​
337#### Returns
338​
339`boolean`
340​
341***
342​
343### subscribe()
344​
345```ts
346subscribe(listener: QueryObserverListener): () => void;
347```
348​
349Defined in: [packages/query-core/src/subscribable.ts:27](https://github.com/TanStack/query/blob/main/packages/query-core/src/subscribable.ts#L27)
350​
351Registers a listener to be called on every update this object notifies about. Returns a function
352that removes the listener again β€” call it to stop listening. The base class never drops a listener
353on its own, though some subclasses clear all of theirs in `destroy()`.
354​
355#### Parameters
356​
357##### listener
358​
359`QueryObserverListener`
360​
361Called on each update, with whatever the subclass passes to its subscribers.
362​
363#### Returns
364​
365```ts
366(): void;
367```
368​
369##### Returns
370​
371`void`
372​
373#### Example
374​
375```ts
376const unsubscribe = subscribable.subscribe(() => {
377 // react to the update
378})
379​
380unsubscribe()
381```
382​
383#### Inherited from
384​
385```ts
386Subscribable.subscribe
387```
388​
389***
390​
391### trackProp()
392​
393```ts
394trackProp(key:
395 | "error"
396 | "data"
397 | "isError"
398 | "isPending"
399 | "isLoading"
400 | "isLoadingError"
401 | "isRefetchError"
402 | "isSuccess"
403 | "isPlaceholderData"
404 | "status"
405 | "dataUpdatedAt"
406 | "errorUpdatedAt"
407 | "failureCount"
408 | "failureReason"
409 | "errorUpdateCount"
410 | "isFetched"
411 | "isFetchedAfterMount"
412 | "isFetching"
413 | "isInitialLoading"
414 | "isPaused"
415 | "isRefetching"
416 | "isStale"
417 | "isEnabled"
418 | "refetch"
419 | "fetchStatus"): void;
420```
421​
422Defined in: [packages/query-core/src/queryObserver.ts:350](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L350)
423​
424Records that the given `QueryObserverResult` property was read, so a subsequent update only
425notifies this observer if a tracked property actually changed. Normally called indirectly via
426[QueryObserver#trackResult](#trackresult)'s proxy; exposed directly for adapters that track property
427access themselves (e.g. through their own reactivity system) instead of via the proxy.
428​
429#### Parameters
430​
431##### key
432​
433`"error"` | `"data"` | `"isError"` | `"isPending"` | `"isLoading"` | `"isLoadingError"` | `"isRefetchError"` | `"isSuccess"` | `"isPlaceholderData"` | `"status"` | `"dataUpdatedAt"` | `"errorUpdatedAt"` | `"failureCount"` | `"failureReason"` | `"errorUpdateCount"` | `"isFetched"` | `"isFetchedAfterMount"` | `"isFetching"` | `"isInitialLoading"` | `"isPaused"` | `"isRefetching"` | `"isStale"` | `"isEnabled"` | `"refetch"` | `"fetchStatus"`
434​
435#### Returns
436​
437`void`
438​
439***
440​
441### trackResult()
442​
443```ts
444trackResult(result: QueryObserverResult<TData, TError>, onPropTracked?: (key:
445 | "error"
446 | "data"
447 | "isError"
448 | "isPending"
449 | "isLoading"
450 | "isLoadingError"
451 | "isRefetchError"
452 | "isSuccess"
453 | "isPlaceholderData"
454 | "status"
455 | "dataUpdatedAt"
456 | "errorUpdatedAt"
457 | "failureCount"
458 | "failureReason"
459 | "errorUpdateCount"
460 | "isFetched"
461 | "isFetchedAfterMount"
462 | "isFetching"
463 | "isInitialLoading"
464 | "isPaused"
465 | "isRefetching"
466 | "isStale"
467 | "isEnabled"
468 | "refetch"
469| "fetchStatus") => void): QueryObserverResult<TData, TError>;
470```
471​
472Defined in: [packages/query-core/src/queryObserver.ts:331](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L331)
473​
474Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via
475[QueryObserver#trackProp](#trackprop) (and an optional `onPropTracked` callback). Used by framework
476adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on
477properties you actually read" behavior.
478​
479#### Parameters
480​
481##### result
482​
483[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
484​
485##### onPropTracked?
486​
487(`key`:
488 \| `"error"`
489 \| `"data"`
490 \| `"isError"`
491 \| `"isPending"`
492 \| `"isLoading"`
493 \| `"isLoadingError"`
494 \| `"isRefetchError"`
495 \| `"isSuccess"`
496 \| `"isPlaceholderData"`
497 \| `"status"`
498 \| `"dataUpdatedAt"`
499 \| `"errorUpdatedAt"`
500 \| `"failureCount"`
501 \| `"failureReason"`
502 \| `"errorUpdateCount"`
503 \| `"isFetched"`
504 \| `"isFetchedAfterMount"`
505 \| `"isFetching"`
506 \| `"isInitialLoading"`
507 \| `"isPaused"`
508 \| `"isRefetching"`
509 \| `"isStale"`
510 \| `"isEnabled"`
511 \| `"refetch"`
512 \| `"fetchStatus"`) => `void`
513​
514#### Returns
515​
516[`QueryObserverResult`](../type-aliases/QueryObserverResult.md)\<`TData`, `TError`\>
517​
518***
519​
520### updateResult()
521​
522```ts
523updateResult(): void;
524```
525​
526Defined in: [packages/query-core/src/queryObserver.ts:733](https://github.com/TanStack/query/blob/main/packages/query-core/src/queryObserver.ts#L733)
527​
528Recomputes and stores the current result from the current query/options, notifying listeners
529if it changed. Framework adapters call this right after subscribing to make sure no query
530update was missed in the gap between creating the observer and subscribing to it.
531​
532#### Returns
533​
534`void`