createApi
createApi
createApi
createApi
is the core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. It generates an "API slice" structure that contains Redux logic (and optionally React hooks) that encapsulate the data fetching and caching process for you.
Parameters
createApi
accepts a single configuration object parameter with the following options:
baseQuery
baseQuery
baseQuery function arguments
args
- The return value of thequery
function for a given endpointapi
- TheBaseQueryApi
object, containingsignal
,dispatch
andgetState
propertiessignal
- AnAbortSignal
object that may be used to abort DOM requests and/or read whether the request is aborted.dispatch
- Thestore.dispatch
method for the corresponding Redux storegetState
- A function that may be called to access the current store state
extraOptions
- The value of the optionalextraOptions
property provided for a given endpoint
baseQuery function signature
endpoints
endpoints
See Anatomy of an endpoint for details on individual properties.
Query endpoint definition
Mutation endpoint definition
How endpoints get used
When defining a key like getPosts
as shown below, it's important to know that this name will become exportable from api
and be able to referenced under api.endpoints.getPosts.useQuery()
, api.endpoints.getPosts.initiate()
and api.endpoints.getPosts.select()
. The same thing applies to mutation
s but they reference useMutation
instead of useQuery
.
tagTypes
tagTypes
reducerPath
reducerPath
serializeQueryArgs
serializeQueryArgs
By default, this function will take the query arguments, sort object keys where applicable, stringify the result, and concatenate it with the endpoint name. This creates a cache key based on the combination of arguments + endpoint name (ignoring object key order), such that calling any given endpoint with the same arguments will result in the same cache key.
keepUnusedDataFor
keepUnusedDataFor
refetchOnMountOrArgChange
refetchOnMountOrArgChange
:::note You can set this globally in createApi
, but you can also override the default value and have more granular control by passing refetchOnMountOrArgChange
to each individual hook call or similarly by passing forceRefetch: true
when dispatching the initiate
action. :::
refetchOnFocus
refetchOnFocus
:::note You can set this globally in createApi
, but you can also override the default value and have more granular control by passing refetchOnFocus
to each individual hook call or when dispatching the initiate
action.
If you specify track: false
when manually dispatching queries, RTK Query will not be able to automatically refetch for you. :::
refetchOnReconnect
refetchOnReconnect
:::note You can set this globally in createApi
, but you can also override the default value and have more granular control by passing refetchOnReconnect
to each individual hook call or when dispatching the initiate
action.
If you specify track: false
when manually dispatching queries, RTK Query will not be able to automatically refetch for you. :::
Anatomy of an endpoint
query
query
(required if no queryFn
provided)
queryFn
queryFn
(required if no query
provided)
Called with the same arguments as baseQuery
, as well as the provided baseQuery
function itself. It is expected to return an object with either a data
or error
property, or a promise that resolves to return such an object.
See also Customizing queries with queryFn.
queryFn function arguments
args
- The argument provided when the query itself is calledapi
- TheBaseQueryApi
object, containingsignal
,dispatch
andgetState
propertiessignal
- AnAbortSignal
object that may be used to abort DOM requests and/or read whether the request is aborted.dispatch
- Thestore.dispatch
method for the corresponding Redux storegetState
- A function that may be called to access the current store state
extraOptions
- The value of the optionalextraOptions
property provided for the endpointbaseQuery
- ThebaseQuery
function provided to the api itself
transformResponse
transformResponse
(optional, not applicable with queryFn
)
In some cases, you may want to manipulate the data returned from a query before you put it in the cache. In this instance, you can take advantage of transformResponse
.
See also Customizing query responses with transformResponse
extraOptions
extraOptions
(optional)
Passed as the third argument to the supplied baseQuery
function
providesTags
providesTags
(optional, only for query endpoints)
See also Providing cache data.
invalidatesTags
invalidatesTags
(optional, only for mutation endpoints)
See also Invalidating cache data.
keepUnusedDataFor
keepUnusedDataFor
(optional, only for query endpoints)
Overrides the api-wide definition of keepUnusedDataFor
for this endpoint only.
onQueryStarted
onQueryStarted
(optional)
Available to both queries and mutations.
A function that is called when you start each individual query or mutation. The function is called with a lifecycle api object containing properties such as queryFulfilled
, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
Can be used in mutations
for optimistic updates.
Lifecycle API properties
dispatch
- The dispatch method for the store.getState
- A method to get the current state for the store.extra
-extra
as provided asthunk.extraArgument
to theconfigureStore
getDefaultMiddleware
option.requestId
- A unique ID generated for the query/mutation.queryFulfilled
- A Promise that will resolve with the (transformed) query result. If the query fails, this Promise will reject with the error. This allows you toawait
for the query to finish.getCacheEntry
- A function that gets the current value of the cache entry.updateCachedData
(query endpoints only) - A function that accepts a 'recipe' callback specifying how to update the data for the corresponding cache at the time it is called. This usesimmer
internally, and updates can be written 'mutably' while safely producing the next immutable state.
onCacheEntryAdded
onCacheEntryAdded
(optional)
Available to both queries and mutations.
A function that is called when a new cache entry is added, i.e. when a new subscription for the endpoint + query parameters combination is created. The function is called with a lifecycle api object containing properties such as cacheDataLoaded
& cacheDataRemoved
, allowing code to be run when a cache entry is added, when cache data is loaded, and when the cache entry is removed (i.e. throughout the lifecycle of a cache entry).
Can be used for streaming updates.
Cache Lifecycle API properties
dispatch
- The dispatch method for the store.getState
- A method to get the current state for the store.extra
-extra
as provided asthunk.extraArgument
to theconfigureStore
getDefaultMiddleware
option.requestId
- A unique ID generated for the cache entry.cacheEntryRemoved
- A Promise that allows you to wait for the point in time when the cache entry has been removed from the cache, by not being used/subscribed to any more in the application for too long or by dispatchingapi.util.resetApiState
.cacheDataLoaded
- A Promise that will resolve with the first value for this cache key. This allows you toawait
until an actual value is in the cache. Note: If the cache entry is removed from the cache before any value has ever been resolved, this Promise will reject withnew Error('Promise never resolved before cacheEntryRemoved.')
to prevent memory leaks. You can just re-throw that error (or not handle it at all) - it will be caught outside ofcacheEntryAdded
.getCacheEntry
- A function that gets the current value of the cache entry.updateCachedData
(query endpoints only) - A function that accepts a 'recipe' callback specifying how to update the data at the time it is called. This usesimmer
internally, and updates can be written 'mutably' while safely producing the next immutable state.
Return value
Last updated