Query
TheQuery class represents a single query instance in the cache. It manages the lifecycle of a query, including fetching, caching, and state management.
Import
Constructor
Type Parameters
type
default:"unknown"
The type of data returned by the query function
type
default:"DefaultError"
The type of error that can be thrown
type
default:"TQueryFnData"
The type of data after transformation
type
default:"QueryKey"
The type of the query key
Properties
state
queryKey
queryHash
options
Methods
fetch
cancel
invalidate
setState
setData
isStale
isStaleByTime
destroy
Examples
Accessing Query State
Finding Queries
Manually Invalidating Queries
Setting Query Data Manually
Checking Query Staleness
Subscribing to Query Changes
Canceling Queries
Removing Queries
Query Metadata
Fetching with Options
Query State
The query state object contains:'pending' | 'error' | 'success'
The current status of the query
'fetching' | 'paused' | 'idle'
The fetch status of the query
TData | undefined
The data returned by the query function
TError | null
The error thrown by the query function (only set on error)
number
The number of times the data has been updated
number
Timestamp when data was last updated
number
The number of times the query has errored
number
Timestamp when error was last updated
number
The number of consecutive fetch failures
TError | null
The reason for the last fetch failure
boolean
Whether the query has been invalidated
FetchMeta | null
Additional metadata about the fetch
Notes
Queryis a low-level class typically created and managed byQueryCache- Each unique query key gets its own
Queryinstance - Queries are kept in cache based on
gcTime(garbage collection time) - The
queryHashis used for efficient internal lookups - Queries support multiple concurrent observers (e.g., multiple components using the same query)
- State changes trigger notifications to observers and cache subscribers
- Queries automatically refetch based on staleTime and other configuration
- The
fetch()method is used internally by observers to trigger data fetching - Use
QueryClientmethods instead of directly manipulating queries in most cases