Skip to main content

Query

The Query 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

The current state of the query.

queryKey

The unique key for this query.

queryHash

A hashed version of the query key used for internal lookups.

options

The query configuration options.

Methods

fetch

Fetch or refetch the query data.

cancel

Cancel any ongoing query fetches.

invalidate

Mark the query as stale/invalidated.

setState

Update the query state.

setData

Manually set the query data.

isStale

Check if the query is stale based on staleTime.

isStaleByTime

Check if the query is stale based on a specific stale time.

destroy

Clean up and remove the query.

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

  • Query is a low-level class typically created and managed by QueryCache
  • Each unique query key gets its own Query instance
  • Queries are kept in cache based on gcTime (garbage collection time)
  • The queryHash is 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 QueryClient methods instead of directly manipulating queries in most cases