Dependent queries with enabled flag in Angular
In Angular Query, dependent queries can be implemented using the enabled option in injectQuery. A query will not execute until a condition is met. For example, a projects query can depend on a user query by setting enabled to !!this.userQuery.data()?.id, which ensures the projects query only runs after the user id is available.
injectQuery for dependent queries in Angular
The injectQuery function in Angular Query allows dependent queries by accepting a queryKey that can reference data from other queries. The queryKey can include this.userQuery.data()?.id to establish the dependency chain, and the enabled option controls when execution occurs.
injectQueries under development for Angular
As of this documentation, injectQueries is under development for Angular Query and is not yet available for use.
isStale return value
The isStale return value is a boolean that will be true if the data in the cache is invalidated or if the data is older than the given staleTime.
isPlaceholderData return value
The isPlaceholderData return value is a boolean that will be true if the data shown is the placeholder data.
isFetched return value
The isFetched return value is a boolean that will be true if the query has been fetched.
isFetchedAfterMount return value
The isFetchedAfterMount return value is a boolean that will be true if the query has been fetched after the component mounted. This property can be used to not show any previously cached data.
fetchStatus return value
The fetchStatus return value is of type FetchStatus and can be: 'fetching' (true whenever the queryFn is executing, including initial pending and background refetches), 'paused' (the query wanted to fetch but has been paused), or 'idle' (the query is not fetching).
isFetching return value
The isFetching return value is a boolean derived from the fetchStatus variable for convenience. It is true whenever the queryFn is executing.
isLoading return value
The isLoading return value is a boolean that is true whenever the first fetch for a query is in-flight. It is the same as isFetching && isPending.
isInitialLoading return value deprecated
The isInitialLoading return value is deprecated and is an alias for isLoading. It will be removed in the next major version.
isPaused return value
The isPaused return value is a boolean derived from the fetchStatus variable for convenience. It is true when the query wanted to fetch but has been paused.
isEnabled return value
The isEnabled return value is a boolean that is true if this query observer is enabled, false otherwise.
useQuery hook signature and parameters
The useQuery hook accepts two parameters: an options object and an optional QueryClient. The options object includes: queryKey (required, unknown[]), queryFn (required unless default defined, receives QueryFunctionContext), gcTime, enabled, networkMode, initialData, initialDataUpdatedAt, meta, notifyOnChangeProps, placeholderData, queryKeyHashFn, refetchInterval, refetchIntervalInBackground, refetchOnMount, refetchOnReconnect, refetchOnWindowFocus, retry, retryOnMount, retryDelay, select, staleTime, structuralSharing, subscribed, and throwOnError.
isRefetching return value
The isRefetching return value is a boolean that is true whenever a background refetch is in-flight, which does not include initial pending. It is the same as isFetching && !isPending.
useQuery return values and state properties
useQuery returns an object containing: data (TData, defaults to undefined), dataUpdatedAt (number), error (null | TError, defaults to null), errorUpdateCount (number), errorUpdatedAt (number), failureCount (number), failureReason (null | TError), fetchStatus (FetchStatus), isError (boolean), isFetched (boolean), isFetchedAfterMount (boolean), isFetching (boolean), isInitialLoading (boolean, deprecated), isLoading (boolean), isLoadingError (boolean), isPaused (boolean), isPending (boolean), isPlaceholderData (boolean), isRefetchError (boolean), isRefetching (boolean), isStale (boolean), isSuccess (boolean), isEnabled (boolean), promise (Promise<TData>), refetch (function), and status (QueryStatus).
queryKey parameter
The queryKey is a required parameter of type unknown[]. It is hashed into a stable hash and used to identify the query. The query will automatically update when this key changes, as long as enabled is not set to false.
queryFn parameter
The queryFn is a function of type (context: QueryFunctionContext) => Promise<TData>. It is required unless a default query function has been defined. It must return a promise that will either resolve data or throw an error. The data cannot be undefined.
enabled parameter for disabling and dependent queries
The enabled parameter is of type boolean | (query: Query) => boolean. Set it to false to disable the query from automatically running. It can be used for dependent queries.
retry parameter configuration
The retry parameter can be: false (failed queries will not retry), true (failed queries will retry infinitely), a number like 3 (failed queries retry until that count is reached), or a function (failureCount: number, error: TError) => boolean to determine if retry should be attempted. failureCount starts at 0 for the first retry. Defaults to 3 on the client and 0 on the server.
retryOnMount parameter
The retryOnMount parameter is of type boolean | (query: Query) => boolean. If set to false, the query will not be retried on mount if it contains an error and has no data. Defaults to true. If set to a function, it will be executed with the query to compute the value.
retryDelay parameter
The retryDelay parameter is of type number | (retryAttempt: number, error: TError) => number. It receives a retryAttempt integer and the actual Error and returns the delay in milliseconds before the next attempt. Examples: attempt => Math.min(attempt > 1 ? 2 ** attempt * 1000 : 1000, 30 * 1000) for exponential backoff, or attempt => attempt * 1000 for linear backoff.
queryKeyHashFn parameter
The queryKeyHashFn parameter is of type (queryKey: QueryKey) => string and is optional. If specified, this function is used to hash the queryKey to a string.
refetchInterval parameter
The refetchInterval parameter is of type number | false | ((query: Query) => number | false | undefined) and is optional. If set to a number, all queries will continuously refetch at this frequency in milliseconds. If set to a function, it will be executed with the query to compute a frequency.
refetchIntervalInBackground parameter
The refetchIntervalInBackground parameter is of type boolean and is optional. If set to true, queries set to continuously refetch with a refetchInterval will continue to refetch while their tab/window is in the background.
refetchOnMount parameter
The refetchOnMount parameter is of type boolean | 'always' | ((query: Query) => boolean | 'always') and is optional. It defaults to true. If true, the query will refetch on mount if the data is stale. If false, the query will not refetch on mount. If 'always', the query will always refetch on mount except when staleTime: 'static' is used. If a function, it will be executed with the query to compute the value.
refetchOnWindowFocus parameter
The refetchOnWindowFocus parameter is of type boolean | 'always' | ((query: Query) => boolean | 'always') and is optional. It defaults to true. If true, the query will refetch on window focus if the data is stale. If false, the query will not refetch on window focus. If 'always', the query will always refetch on window focus except when staleTime: 'static' is used. If a function, it will be executed with the query to compute the value.
refetchOnReconnect parameter
The refetchOnReconnect parameter is of type boolean | 'always' | ((query: Query) => boolean | 'always') and is optional. It defaults to true. If true, the query will refetch on reconnect if the data is stale. If false, the query will not refetch on reconnect. If 'always', the query will always refetch on reconnect except when staleTime: 'static' is used. If a function, it will be executed with the query to compute the value.
notifyOnChangeProps parameter
The notifyOnChangeProps parameter is of type string[] | 'all' | (() => string[] | 'all' | undefined) and is optional. If set, the component will only re-render if any of the listed properties change. For example, ['data', 'error'] will only re-render when data or error change. If set to 'all', the component opts out of smart tracking and re-renders whenever a query is updated. If a function, it will be executed to compute the list of properties. By default, access to properties is tracked and the component only re-renders when tracked properties change.
select parameter for data transformation
The select parameter is of type (data: TData) => unknown and is optional. It can be used to transform or select a part of the data returned by the query function. It affects the returned data value but does not affect what is stored in the query cache. The select function will only run if data changed or if the reference to the select function itself changes. To optimize, wrap the function in useCallback.
initialData parameter
The initialData parameter is of type TData | (() => TData) and is optional. If set, this value will be used as the initial data for the query cache as long as the query hasn't been created or cached yet. If set to a function, it will be called once during shared/root query initialization and expected to synchronously return the initialData. Initial data is considered stale by default unless staleTime has been set. initialData is persisted to the cache.
initialDataUpdatedAt parameter
The initialDataUpdatedAt parameter is of type number | (() => number | undefined) and is optional. If set, this value will be used as the time in milliseconds of when the initialData itself was last updated.
placeholderData parameter
The placeholderData parameter is of type TData | (previousValue: TData | undefined, previousQuery: Query | undefined) => TData and is optional. If set, this value will be used as the placeholder data for this particular query observer while the query is still in the pending state. placeholderData is not persisted to the cache. If a function is provided, the first argument will be previously watched query data if available, and the second argument will be the complete previousQuery instance.
subscribed parameter
The subscribed parameter is of type boolean and is optional. It defaults to true. If set to false, this instance of useQuery will not be subscribed to the cache. This means it won't trigger queryFn on its own and won't receive updates if data gets into cache by other means.
throwOnError parameter
The throwOnError parameter is of type undefined | boolean | (error: TError, query: Query) => boolean and is optional. It defaults to false. Set to true if errors should be thrown in the render phase and propagate to the nearest error boundary. Set to false to disable suspense's default behavior of throwing errors to the error boundary. If a function, it will be passed the error and the query, and should return a boolean indicating whether to show the error in an error boundary (true) or return the error as state (false).
meta parameter for storing query metadata
The meta parameter is of type Record<string, unknown> and is optional. If set, it stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the query is available and is also part of the QueryFunctionContext provided to the queryFn.
status return value
The status return value is of type QueryStatus and will be: 'pending' if there's no cached data and no query attempt was finished yet; 'error' if the query attempt resulted in an error with the error property containing the error from the attempted fetch; 'success' if the query has received a response with no errors and is ready to display its data, or if enabled is false and hasn't been fetched yet, data is the first initialData supplied to the query on initialization.
isPending, isSuccess, isError return values
isPending, isSuccess, and isError are boolean values derived from the status variable for convenience. isPending is true when status is 'pending', isSuccess is true when status is 'success', and isError is true when status is 'error'.
isLoadingError and isRefetchError return values
isLoadingError is a boolean that will be true if the query failed while fetching for the first time. isRefetchError is a boolean that will be true if the query failed while refetching.
data return value
The data return value is of type TData and defaults to undefined. It is the last successfully resolved data for the query.
dataUpdatedAt return value
The dataUpdatedAt return value is of type number and represents the timestamp for when the query most recently returned the status as 'success'.
error return value
The error return value is of type null | TError and defaults to null. It is the error object for the query if an error was thrown.
errorUpdatedAt return value
The errorUpdatedAt return value is of type number and represents the timestamp for when the query most recently returned the status as 'error'.
failureCount return value
The failureCount return value is of type number and represents the failure count for the query. It is incremented every time the query fails and reset to 0 when the query succeeds.
failureReason return value
The failureReason return value is of type null | TError and represents the failure reason for the query retry. It is reset to null when the query succeeds.
errorUpdateCount return value
The errorUpdateCount return value is of type number and represents the sum of all errors.
refetch function
The refetch function is of type (options: { throwOnError: boolean, cancelRefetch: boolean }) => Promise<UseQueryResult>. It is a function to manually refetch the query. If the query errors, the error will only be logged. If you want an error to be thrown, pass the throwOnError: true option. The cancelRefetch option defaults to true. Per default, a currently running request will be cancelled before a new request is made. When set to false, no refetch will be made if there is already a request running.
promise return value
The promise return value is of type Promise<TData> and is a stable promise that will be resolved with the data of the query. It requires the experimental_prefetchInRender feature flag to be enabled on the QueryClient.
queryClient parameter
The queryClient parameter is of type QueryClient and is optional. Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.