Customizing queries#
RTK Query is agnostic as to how your requests resolve. You can use any library you like to handle requests, or no library at all. RTK Query provides reasonable defaults expected to cover the majority of use cases, while also allowing room for customization to alter query handling to fit specific needs.
Customizing queries with baseQuery#
The default method to handle queries is via the baseQuery option on createApi, in combination with the query option on an endpoint definition.
To process queries, endpoints are defined with a query option, which passes its return value to a common baseQuery function used for the API.
By default, RTK Query ships with fetchBaseQuery, which is a lightweight fetch wrapper that automatically handles request headers and response parsing in a manner similar to common libraries like axios. If fetchBaseQuery alone does not meet your needs, you can customize its behaviour with a wrapper function, or create your own baseQuery function from scratch for createApi to use.
See also baseQuery API Reference.
Implementing a custom baseQuery#
RTK Query expects a baseQuery function to be called with three arguments: args, api, and extraOptions. It is expected to return an object with either a data or error property, or a promise that resolves to return such an object.
baseQuery function arguments#
baseQuery function return value#
- Expected success result format
- Expected error result format
note
This format is required so that RTK Query can infer the return types for your responses.
At its core, a baseQuery function only needs to have the minimum return value to be valid; an object with a data or error property. It is up to the user to determine how they wish to use the provided arguments, and how requests are handled within the function itself.
fetchBaseQuery defaults#
For fetchBaseQuery specifically, the return type is as follows:
- Expected success result format with fetchBaseQuery
- Expected error result format with fetchBaseQuery
Customizing query responses with transformResponse#
Individual endpoints on createApi accept a transformResponse property which allows manipulation of the data returned by a query or mutation before it hits the cache.
transformResponse is called with the data that a successful baseQuery returns for the corresponding endpoint, and the return value of transformResponse is used as the cached data associated with that endpoint call.
By default, the payload from the server is returned directly.
- TypeScript
- JavaScript
To change it, provide a function that looks like:
transformResponse is also called with the meta property returned from the baseQuery, which can be used while determining the transformed response. The value for meta is dependent on the baseQuery used.
While there is less need to store the response in a normalized lookup table with RTK Query managing caching data, transformResponse can be leveraged to do so if desired.
createEntityAdapter can also be used with transformResponse to normalize data, while also taking advantage of other features provided by createEntityAdapter, including providing an ids array, using sortComparer to maintain a consistently sorted list, as well as maintaining strong TypeScript support.
See also Websocket Chat API with a transformed response shape for an example of transformResponse normalizing response data in combination with createEntityAdapter, while also updating further data using streaming updates.
Customizing queries with queryFn#
Individual endpoints on createApi accept a queryFn property which allows a given endpoint to ignore baseQuery for that endpoint by providing an inline function determining how that query resolves.
This can be useful for scenarios where you want to have particularly different behaviour for a single endpoint, or where the query itself is not relevant. Such situations may include:
- One-off queries that use a different base URL
- One-off queries that use different request handling, such as automatic re-tries
- One-off queries that use different error handling behaviour
- Performing multiple requests with a single query (example)
- Leveraging invalidation behaviour with no relevant query (example)
- Using Streaming Updates with no relevant initial request (example)
See also queryFn API Reference for the type signature and available options.
Implementing a queryFn#
In order to use queryFn, it can be treated as an inline baseQuery. It will be called with the same arguments as baseQuery, as well as the provided baseQuery function itself (arg, api, extraOptions, and baseQuery). Similarly to baseQuery, it is expected to return an object with either a data or error property, or a promise that resolves to return such an object.
queryFn function arguments#
queryFn function return value#
- Expected success result format
- Expected error result format
Examples - baseQuery#
Axios baseQuery#
This example implements a very basic axios-based baseQuery utility.
- TypeScript
- JavaScript
GraphQL baseQuery#
This example implements a very basic GraphQL-based baseQuery.
- TypeScript
- JavaScript
Automatic re-authorization by extending fetchBaseQuery#
This example wraps fetchBaseQuery such that when encountering a 401 Unauthorized error, an additional request is sent to attempt to refresh an authorization token, and re-try to initial query after re-authorizing.
- TypeScript
- JavaScript
Automatic retries#
RTK Query exports a utility called retry that you can wrap the baseQuery in your API definition with. It defaults to 5 attempts with a basic exponential backoff.
The default behavior would retry at these intervals:
- 600ms * random(0.4, 1.4)
- 1200ms * random(0.4, 1.4)
- 2400ms * random(0.4, 1.4)
- 4800ms * random(0.4, 1.4)
- 9600ms * random(0.4, 1.4)
- TypeScript
- JavaScript
In the event that you didn't want to retry on a specific endpoint, you can just set maxRetries: 0.
info
It is possible for a hook to return data and error at the same time. By default, RTK Query will keep whatever the last 'good' result was in data until it can be updated or garbage collected.
Bailing out of error re-tries#
The retry utility has a fail method property attached which can be used to bail out of retries immediately. This can be used for situations where it is known that additional re-tries would be guaranteed to all fail and would be redundant.
- TypeScript
- JavaScript
Adding Meta information to queries#
A baseQuery can also include a meta property in its return value. This can be beneficial in cases where you may wish to include additional information associated with the request such as a request ID or timestamp.
In such a scenario, the return value would look like so:
- Expected success result format with meta
- Expected error result format with meta
- TypeScript
- JavaScript
Constructing a Dynamic Base URL using Redux state#
In some cases, you may wish to have a dynamically altered base url determined from a property in your Redux state. A baseQuery has access to a getState method that provides the current store state at the time it is called. This can be used to construct the desired url using a partial url string, and the appropriate data from your store state.
- TypeScript
- JavaScript
Examples - transformResponse#
Unpacking deeply nested GraphQL data#
- TypeScript
- JavaScript
Normalizing data with createEntityAdapter#
In the example below, transformResponse is used in conjunction with createEntityAdapter to normalize the data before storing it in the cache.
For a response such as:
The normalized cache data will be stored as:
- TypeScript
- JavaScript
Examples - queryFn#
Using a no-op queryFn#
In certain scenarios, you may wish to have a query or mutation where sending a request or returning data is not relevant for the situation. Such a scenario would be to leverage the invalidatesTags property to force re-fetch specific tags that have been provided to the cache.
See also providing errors to the cache to see additional detail and an example for such a scenario to 'refetch errored queries'.
- TypeScript
- JavaScript
Streaming data with no initial request#
RTK Query provides the ability for an endpoint to send an initial request for data, followed up with recurring streaming updates that perform further updates to the cached data as the updates occur. However, the initial request is optional, and you may wish to use streaming updates without any initial request fired off.
In the example below, a queryFn is used to populate the cache data with an empty array, with no initial request sent. The array is later populated using streaming updates via the onCacheEntryAdded endpoint option, updating the cached data as it is received.
- TypeScript
- JavaScript
Performing multiple requests with a single query#
In the example below, a query is written to fetch all posts for a random user. This is done using a first request for a random user, followed by getting all posts for that user. Using queryFn allows the two requests to be included within a single query, avoiding having to chain that logic within component code.
- TypeScript
- JavaScript