Skip to main content
The QueryObserver is the underlying mechanism that powers hooks like useQuery. It subscribes to a query and notifies listeners when the query state changes.

Constructor

Creates a new QueryObserver instance.
QueryClient
required
The QueryClient instance to use.
QueryObserverOptions
required
Options for the observer.

Example

Methods

subscribe

Subscribes to the observer and receives updates when the query state changes.
(result: QueryObserverResult<TData, TError>) => void
required
Function called when the query result changes.
function
Returns an unsubscribe function.

Example

setOptions

Updates the observer options. This will trigger a re-evaluation of the query.
QueryObserverOptions
required
New options for the observer.

Example

getCurrentResult

Returns the current result of the query.
QueryObserverResult
Returns the current query result.

Example

getCurrentQuery

Returns the current Query instance being observed.
Query
Returns the Query instance.

getOptimisticResult

Returns an optimistic result based on the provided options without subscribing.
DefaultedQueryObserverOptions
required
Options to compute the optimistic result.
QueryObserverResult
Returns an optimistic query result.

refetch

Manually refetches the query.
RefetchOptions
Options for refetching.
Promise
Returns a promise that resolves with the query result.

Example

fetchOptimistic

Fetches the query with the provided options and returns the result.
QueryObserverOptions
required
Options for the fetch.
Promise
Returns a promise that resolves with the query result.

destroy

Destroys the observer and cleans up all subscriptions and timers.

Example

trackResult

Returns a proxied version of the result that tracks which properties are accessed.
QueryObserverResult
required
The result to track.
(key: keyof QueryObserverResult) => void
Callback called when a property is accessed.
QueryObserverResult
Returns a proxied result that tracks property access.

trackProp

Manually track a specific property.
keyof QueryObserverResult
required
The property key to track.

Lifecycle

When you subscribe to a QueryObserver:
  1. The observer adds itself to the query’s list of observers
  2. If needed, the query will fetch data on mount
  3. The observer sets up stale and refetch interval timers
  4. When the query state changes, the observer notifies all listeners
  5. When you unsubscribe, the observer cleans up timers and removes itself from the query

Usage Example

Here’s a complete example showing how to use QueryObserver:

Internal Methods

The following methods are used internally and are not typically needed:

shouldFetchOnReconnect

Determines if the query should refetch when reconnecting.

shouldFetchOnWindowFocus

Determines if the query should refetch when the window regains focus.

updateResult

Updates the current result and notifies listeners if changed.

onQueryUpdate

Called when the query is updated.