injectQuery
Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.Signature
Parameters
A function that returns query options. The function is run in a reactive context, similar to Angular’s
computed. This allows signals to be inserted into the options, making the query reactive.CreateQueryOptions properties:queryKey- A unique key for the queryqueryFn- The function that the query will use to fetch dataenabled- Whether the query should run automaticallystaleTime- Time in milliseconds before data is considered stalegcTime- Time in milliseconds before inactive queries are garbage collected- And other standard query options
Additional configuration for the query injection.
Returns
A signal-based query result object with the following properties:
data- The data returned by the query functionerror- The error object if the query failedstatus- The status of the query (pending, error, success)isPending- Boolean indicating if the query is in pending stateisError- Boolean indicating if the query failedisSuccess- Boolean indicating if the query succeededrefetch- Function to manually refetch the query- And other standard query result properties
Usage
Basic example
Reactive example with signals
Similar tocomputed from Angular, the function passed to injectQuery will be run in the reactive context. In the example below, the query will be automatically enabled and executed when the filter signal changes to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
Using with custom injector
Type Overloads
With defined initial data
initialData is provided and defined, the query result is guaranteed to have data available immediately.
With undefined initial data
initialData is not provided or is undefined, the query result data may be undefined initially.
Notes
- Must be called within an injection context (constructor, field initializer, or factory function) unless the
injectoroption is provided - The query function is reactive and will re-run when any signals used inside it change
- The query is automatically managed and cleaned up when the component/service is destroyed