Build query hooks
A framework adapter needs a reactive query result.
TanStack · Class
QueryObserver observes one query and produces a QueryObserverResult from its state. It supports framework adapters and direct, framework-independent subscriptions.
QueryObserver connects a QueryClient to one query and turns query state into a QueryObserverResult. It recalculates when the query or observer options change, and subscribers receive notifications when the computed result changes. Use getCurrentResult for a snapshot or subscribe for ongoing updates.
new QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>(client: QueryClient, options: QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>): QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>| Name | Type | Description |
|---|---|---|
client | QueryClient | The QueryClient used to access and observe the query cache. |
options | QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey> | Configuration describing the query and result typing. |
A QueryObserver instance that computes results for and notifies subscribers about one observed query.
import { QueryClient, QueryObserver } from '@tanstack/query-core'
const client = new QueryClient()
const observer = new QueryObserver(client, {
queryKey: ['todos'],
queryFn: async () => [{ id: 1, title: 'Learn QueryObserver' }],
})
const unsubscribe = observer.subscribe((result) => {
if (result.isSuccess) console.log(result.data)
})
observer.refetch().finally(() => unsubscribe())Creates a core observer, subscribes to result changes, triggers a fetch, and removes the subscription afterward.
A framework adapter needs a reactive query result.
A non-framework service needs cache-backed updates.
A client changes which cached query it tracks.
QueryObserver watches one query in the QueryCache and computes a QueryObserverResult. It recomputes and notifies subscribers when the query or the observer options change.
Follow-up: How would you consume a result without subscribing? Call getCurrentResult(), but remember that it returns only the latest point-in-time result.
Construct it with a QueryClient and QueryObserverOptions. The options describe the query being observed, and the constructor returns a QueryObserver instance.
Follow-up: How can the observed query be changed? Update the observer's options with the appropriate inherited option-update mechanism, causing the current query and result to be recalculated.
subscribe() registers a listener for observer-result changes and returns an unsubscribe function. Use getCurrentResult() when a synchronous snapshot is sufficient.
Follow-up: Why should a subscriber be removed? Because the returned unsubscribe function stops future notifications when the consumer no longer needs the observer.
QueryClientQueryObserverOptionsQueryObserverResultInfiniteQueryObserveruseQuery