Skip to main content

 

API Slices: Utilities

The API slice object includes various utilities that can be used for cache management, such as implementing optimistic updates, as well implementing server side rendering.

These are included as api.util inside the API object. The type of api.util is exported as ApiUtil<Definitions, ReducerPath, TagTypes>, where the type parameters match the endpoint definitions, reducerPath, and tag types of the API.

info

Some of the TS types on this page are pseudocode to illustrate intent, as the actual internal types are fairly complex.

updateQueryData​

A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.

Signature​

const updateQueryData = (
endpointName: string,
arg: any,
updateRecipe: (draft: Draft<CachedState>) => void,
updateProvided?: boolean,
) => ThunkAction<PatchCollection, PartialState, any, AnyAction>

interface PatchCollection {
patches: Patch[]
inversePatches: Patch[]
undo: (options?: { ifUnchanged?: boolean }) => void
}

Parameters​

  • endpointName: a string matching an existing endpoint name
  • arg: an argument matching that used for a previous query call, used to determine which cached dataset needs to be updated
  • updateRecipe: an Immer produce callback that can apply changes to the cached state
  • updateProvided: a boolean indicating whether the endpoint's provided tags should be re-calculated based on the updated cache. Defaults to false.

Description​

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as 'getPost'), any relevant query arguments, and a callback function. The callback receives an Immer-wrapped draft of the current state, and may modify the draft to match the expected results after the mutation completes successfully.

The thunk returns an object containing patches, inversePatches, and an undo function. The patches and inversePatches are generated using Immer's produceWithPatches method. The Patch type is exported from @reduxjs/toolkit/query, and matches Immer's Patch type.

This is typically used as the first step in implementing optimistic updates. The generated inversePatches can be used to revert the updates by calling dispatch(patchQueryData(endpointName, arg, inversePatches)). Alternatively, the undo method can be called directly to achieve the same effect.

Pass undo({ ifUnchanged: true }) to apply the inverse patches only if the cached data is still the same reference stored by this update. If a refetch or another write replaced the data, or the entry was removed, the undo does nothing. For primitive data, the comparison uses Object.is. Calling undo(), undo({}), or undo({ ifUnchanged: false }) applies the inverse patches unconditionally, as before.

A skipped undo does not remove the failed mutation's changes from later optimistic updates. Invalidate the relevant tags on error to re-fetch the server data. See Optimistic Updates.

Note that the first two arguments (endpointName and arg) are used to determine which existing cache entry to update. If no existing cache entry is found, the updateRecipe callback will not run.

Example 1​

const patchCollection = dispatch(
api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
draftPosts.push({ id: 1, name: 'Teddy' })
}),
)

In the example above, 'getPosts' is provided for the endpointName, and undefined is provided for arg. This will match a query cache key of 'getPosts(undefined)'.

i.e. it will match a cache entry that may have been created via any of the following calls:

api.endpoints.getPosts.useQuery()

useGetPostsQuery()

useGetPostsQuery(undefined, { ...options })

dispatch(api.endpoints.getPosts.initiate())

dispatch(api.endpoints.getPosts.initiate(undefined, { ...options }))

Example 2​

const patchCollection = dispatch(
api.util.updateQueryData('getPostById', 1, (draftPost) => {
draftPost.name = 'Lilly'
}),
)

In the example above, 'getPostById' is provided for the endpointName, and 1 is provided for arg. This will match a query cache key of 'getPostById(1)'.

i.e. it will match a cache entry that may have been created via any of the following calls:

api.endpoints.getPostById.useQuery(1)

useGetPostByIdQuery(1)

useGetPostByIdQuery(1, { ...options })

dispatch(api.endpoints.getPostById.initiate(1))

dispatch(api.endpoints.getPostById.initiate(1, { ...options }))

upsertQueryData​

A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.

Signature​

const upsertQueryData = <T>(endpointName: string, arg: any, newEntryData: T) =>
ThunkAction<Promise<CacheEntry<T>>, PartialState, any, UnknownAction>

Parameters​

  • endpointName: a string matching an existing endpoint name
  • arg: an argument matching that used for a previous query call, used to determine which cached dataset needs to be updated
  • newEntryValue: the value to be written into the corresponding cache entry's data field

Description​

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as 'getPost'), the appropriate query arg values to construct the desired cache key, and the data to upsert.

If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will overwrite the existing cache entry data.

The thunk executes asynchronously, and returns a promise that resolves when the store has been updated. This includes executing the transformResponse callback if defined for that endpoint.

If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.

Example​

await dispatch(
api.util.upsertQueryData('getPost', { id: 1 }, { id: 1, text: 'Hello!' }),
)

patchQueryData​

A Redux thunk action creator that, when dispatched, applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.

Signature​

const patchQueryData = (
endpointName: string,
arg: any
patches: Patch[],
updateProvided?: boolean
) => ThunkAction<void, PartialState, any, UnknownAction>;

Parameters​

  • endpointName: a string matching an existing endpoint name
  • arg: a cache key, used to determine which cached dataset needs to be updated
  • patches: an array of patches (or inverse patches) to apply to cached state. These would typically be obtained from the result of dispatching updateQueryData
  • updateProvided: a boolean indicating whether the endpoint's provided tags should be re-calculated based on the updated cache. Defaults to false.

Description​

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as 'getPost'), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's produceWithPatches.

This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching patchQueryData with the inversePatches that were generated by updateQueryData earlier.

In cases where it is desired to simply revert the previous changes, it may be preferable to call the undo method returned from dispatching updateQueryData instead.

Example​

const patchCollection = dispatch(
api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
draftPosts.push({ id: 1, name: 'Teddy' })
}),
)

// later
dispatch(
api.util.patchQueryData(
'getPosts',
undefined,
patchCollection.inversePatches,
),
)

// or
patchCollection.undo()

upsertQueryEntries​

A standard Redux action creator that accepts an array of individual cache entry descriptions, and immediately upserts them into the store. This is designed to efficiently bulk-insert many entries at once.

Signature​

/**
* A typesafe single entry to be upserted into the cache
*/
export type NormalizedQueryUpsertEntry<
Definitions extends EndpointDefinitions,
EndpointName extends QueryKeys<Definitions>,
> = {
endpointName: EndpointName
arg: QueryArgFrom<Definitions[EndpointName]>
value: ResultTypeFrom<Definitions[EndpointName]>
}

type UpsertEntriesOptions = {
ignoreEarlierFetches?: boolean
keepRequestState?: boolean
keepUnusedDataTimer?: boolean
}

const upsertQueryEntries = (
entries: NormalizedQueryUpsertEntry[],
options?: UpsertEntriesOptions,
) => PayloadAction<NormalizedQueryUpsertEntry[]>

Parameters​

  • entries: an array of objects that contain the data needed to upsert individual cache entries:
    • endpointName: the name of the endpoint, such as "getPokemon"
    • arg: the full query key argument needed to identify this cache entry, such as "pikachu" (same as you would pass to a useQuery hook or api.endpoints.someEndpoint.select())
    • value: the data to be upserted into this cache entry, exactly as formatted.
  • options (optional): controls how the write interacts with fetches for the same entries. Every option defaults to false, which keeps the behavior described below.
    • ignoreEarlierFetches: if a fetch for an entry is in flight when the write happens, that fetch started before the write, so its data is ignored when it resolves. The fetch still sets the entry's status (and error if it fails). Fetches started after the write are not affected.
    • keepRequestState: entries that already have a request keep their status, requestId, error, startedTimeStamp and fulfilledTimeStamp. Only data (and the provided tags) change. Entries without a request are created as fulfilled.
    • keepUnusedDataTimer: the write does not restart the keepUnusedDataFor timer of entries that already exist. New entries without subscribers still get a normal timer.

Description​

This method is designed as a more efficient approach to bulk-inserting many entries at once than many individual calls to upsertQueryData. As a comparison:

  • upsertQueryData:
    • upserts one cache entry at a time
    • Is async
    • Dispatches 2 separate actions, pending and fulfilled
    • Runs the transformResponse callback if defined for that endpoint, as well as the merge callback if defined
  • upsertQueryEntries:
    • upserts many cache entries at once, and they may be for any combination of endpoints defined in the API
    • Is a single synchronous action
    • Does not run transformResponse, so the provided value fields must already be in the final format expected for that endpoint. However, it will still run the merge callback if defined

Currently, this method has two main use cases. The first is prefilling the cache with data retrieved from storage on app startup. The second is to act as a "pseudo-normalization" tool. RTK Query is not a "normalized" cache. However, there are times when you may want to prefill other cache entries with the contents of another endpoint, such as taking the results of a getPosts list endpoint response and prefilling the individual getPost(id) endpoint cache entries.

If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will overwrite the existing cache entry data.

If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior. Pass ignoreEarlierFetches: true to keep the upserted data instead, since it is newer than the data the in-flight fetch will return.

By default, an upsert also marks an existing entry as fulfilled, clears its error, and restarts its keepUnusedDataFor timer. keepRequestState: true and keepUnusedDataTimer: true turn those off, so the upsert only changes the data.

// A websocket message with the latest version of a post
dispatch(
api.util.upsertQueryEntries(
[{ endpointName: 'getPost', arg: { id: post.id }, value: post }],
{ ignoreEarlierFetches: true, keepRequestState: true },
),
)

Example​

const api = createApi({
endpoints: (build) => ({
getPosts: build.query<Post[], void>({
query: () => '/posts',
async onQueryStarted(_, { dispatch, queryFulfilled }) {
const res = await queryFulfilled
const posts = res.data

// Pre-fill the individual post entries with the results
// from the list endpoint query
dispatch(
api.util.upsertQueryEntries(
posts.map((post) => ({
endpointName: 'getPost',
arg: { id: post.id },
value: post,
})),
),
)
},
}),
getPost: build.query<Post, Pick<Post, 'id'>>({
query: (post) => `post/${post.id}`,
}),
}),
})

removeQueryData​

A Redux thunk action creator that, when dispatched, removes one query cache entry from the store.

Check the alternatives first

RTK Query removes unused cache entries on its own after keepUnusedDataFor seconds, so most apps never need to remove an entry by hand. Depending on what you are trying to do, one of these usually fits better:

  • Get fresh data: invalidateTags or refetch(). Subscribed entries refetch, and entries with no subscribers are removed.
  • Clear everything, such as on logout: resetApiState.
  • Avoid showing data for a previous argument: read currentData instead of data from the query hook, or give the component a React key so it remounts.

Signature​

const removeQueryData = (
endpointName: string,
arg: any,
options?: { onlyIfUnused?: boolean },
) => ThunkAction<boolean, PartialState, any, UnknownAction>

Parameters​

  • endpointName: a string matching an existing query or infinite query endpoint name
  • arg: the query arg used to build the cache key of the entry to remove, the same value you would pass to the query hook or api.endpoints.someEndpoint.select(). The endpoint's serializeQueryArgs is applied.
  • options.onlyIfUnused: if true, the entry is only removed when nothing is subscribed to it. Defaults to false.

Description​

The thunk runs synchronously and returns true if it removed an entry. It returns false if there was no entry for that arg, or if onlyIfUnused is set and the entry still has subscribers.

Removing an entry does the same cleanup as the automatic removal of unused data:

  • A running request for the entry is aborted, and its response is ignored.
  • The entry's keepUnusedDataFor removal timer is cleared.
  • cacheEntryRemoved in onCacheEntryAdded resolves.

If something is still subscribed to the entry when you remove it:

  • useQuery, useQuerySubscription, useInfiniteQuery, and useInfiniteQuerySubscription hooks still mounted for that arg go back to isLoading: true with no data, and fetch the data again.
  • useLazyQuery and useLazyQuerySubscription do not refetch. Their subscription is dropped, and the result goes back to the uninitialized state with no data until you call the trigger function again.
  • Promises returned by initiate() for a request that was running resolve with an AbortError error, and unwrap() rejects with it.
  • Subscriptions created with initiate() outside of a hook are dropped. They do not refetch. isSubscribed() on the initiate() result returns false afterwards, so code that holds that result can check it and call initiate() again.

Pass onlyIfUnused: true if you only want to clear data that nothing on screen is using.

Example​

// The user deleted post 5, so drop its cached data
dispatch(api.util.removeQueryData('getPost', 5))

// Remove the entry only if no component is using it
const removed = dispatch(
api.util.removeQueryData('getPost', 5, { onlyIfUnused: true }),
)

prefetch​

A Redux thunk action creator that can be used to manually trigger pre-fetching of data.

Signature​

type PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean }

const prefetch = (endpointName: string, arg: any, options: PrefetchOptions) =>
ThunkAction<Promise<void>, any, any, UnknownAction>

Parameters​

  • endpointName: a string matching an existing query or infinite query endpoint name
  • args: a cache key, used to determine which cached dataset needs to be updated
  • options: options to determine whether the request should be sent for a given situation:
    • ifOlderThan: if specified, only runs the query if the entry has no data, or if its data is at least this many seconds old. 0 and false behave like passing no options.
    • force: if true, it will ignore the ifOlderThan value if it is set and the query will be run even if it exists in the cache.

Description​

The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as 'getPost'), any relevant query arguments, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.

Dispatching the thunk returns a promise. It resolves once the request finishes, including when the prefetch joined a request that was already running for the same cache entry. If the options decide no request is needed, it resolves right away. The promise never rejects: a failed request still resolves it, and the error is stored in the cache entry as usual. Read the cache entry with a selector if you need to know whether the request succeeded.

Prefetching an infinite query endpoint fetches its first page when the cache entry is empty. See Request Behavior for how prefetch options compare with the other options that force a request. When it has cached data, a prefetch that runs refetches it the same way the endpoint normally refetches.

React Hooks users will most likely never need to use this directly, as the usePrefetch hook will dispatch the thunk action creator result internally as needed when you call the prefetching function supplied by the hook. That function returns the same promise.

Example​

await dispatch(api.util.prefetch('getPosts', undefined, { force: true }))

selectInvalidatedBy​

A selector function that can select query parameters to be invalidated.

Signature​

function selectInvalidatedBy(
state: RootState,
tags: ReadonlyArray<TagDescription<string>>,
): Array<{
endpointName: string
originalArgs: any
queryCacheKey: QueryCacheKey
}>

Parameters​

  • state: the root state
  • tags: a readonly array of invalidated tags, where the provided TagDescription is one of the strings provided to the tagTypes property of the api. e.g.
    • [TagType]
    • [{ type: TagType }]
    • [{ type: TagType, id: number | string }]

Description​

The function accepts two arguments

  • the root state and
  • the cache tags to be invalidated.

It returns an array that contains

  • the endpoint name,
  • the original args and
  • the queryCacheKey.

Example​

const entries = api.util.selectInvalidatedBy(state, ['Post'])
const entries = api.util.selectInvalidatedBy(state, [{ type: 'Post', id: 1 }])
const entries = api.util.selectInvalidatedBy(state, [
{ type: 'Post', id: 1 },
{ type: 'Post', id: 4 },
])

invalidateTags​

A Redux action creator that can be used to manually invalidate cache tags for automated re-fetching.

Signature​

const invalidateTags = (
tags: Array<TagTypes | FullTagDescription<TagTypes>>,
) => ({
type: string,
payload: tags,
})

Parameters​

  • tags: an array of tags to be invalidated, where the provided TagType is one of the strings provided to the tagTypes property of the api. e.g.
    • [TagType]
    • [{ type: TagType }]
    • [{ type: TagType, id: number | string }]

Description​

The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding invalidateTags action type for the api.

Dispatching the result of this action creator will invalidate the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that provides the corresponding tags.

Example​

dispatch(api.util.invalidateTags(['Post']))
dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
dispatch(
api.util.invalidateTags([
{ type: 'Post', id: 1 },
{ type: 'Post', id: 'LIST' },
]),
)

selectCachedArgsForQuery​

A selector function that can select arguments for currently cached queries.

Signature​

function selectCachedArgsForQuery(
state: RootState,
queryName: QueryName,
): Array<QueryArg>

Parameters​

  • state: the root state
  • queryName: a string matching an existing query endpoint name

Description​

The function accepts two arguments

  • the root state and

  • the name of the query

It returns an array that contains arguments used for each entry.

Example​

const args = api.util.selectCachedArgsForQuery(state, 'getPosts')

selectEntriesForEndpoint​

A memoized selector that returns all cache entries for one query or infinite query endpoint.

Signature​

function selectEntriesForEndpoint(
state: RootState,
queryName: QueryName,
): Array<QueryCacheEntry>

type QueryCacheEntry = {
queryCacheKey: string
endpointName: string
status: 'pending' | 'fulfilled' | 'rejected'
originalArgs: QueryArg
data?: ResultType
error?: unknown
requestId: string
startedTimeStamp: number
fulfilledTimeStamp?: number
}

Parameters​

  • state: the root state
  • queryName: a string matching an existing query or infinite query endpoint name

Description​

Returns an array with one item per cache entry for that endpoint. Each item has the same fields as the cache entry in the api state, plus its queryCacheKey. Uninitialized entries are skipped. Infinite query entries also include direction, and their data is the { pages, pageParams } object.

The result is memoized: it returns the same array reference until the api's query state changes.

Example​

const postEntries = api.util.selectEntriesForEndpoint(state, 'getPost')
const loadedPostIds = postEntries
.filter((entry) => entry.status === 'fulfilled')
.map((entry) => entry.originalArgs)

selectAllQueryEntries​

A memoized selector that returns all query and infinite query cache entries for this api.

Signature​

function selectAllQueryEntries(state: RootState): Array<QueryCacheEntry>

Parameters​

  • state: the root state

Description​

Returns the same items as selectEntriesForEndpoint, for every query and infinite query endpoint. Use entry.endpointName to tell them apart. Mutations are not included.

Example​

const entries = api.util.selectAllQueryEntries(state)
const pendingCount = entries.filter(
(entry) => entry.status === 'pending',
).length

resetApiState​

Signature​

const resetApiState = () => ({
type: string,
payload: undefined,
})

Description​

A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.

Note that hooks also track state in local component state and might not fully be reset by resetApiState.

Example​

dispatch(api.util.resetApiState())

getRunningQueriesThunk and getRunningMutationsThunk​

Signature​

getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any>>>
getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>

Description​

Thunks that (if dispatched) return either all running queries or mutations. These returned values can be awaited like promises.

This is useful for SSR scenarios to await all queries (or mutations) triggered in any way, including via hook calls or manually dispatching initiate actions.

Awaiting all currently running queries example
await Promise.all(dispatch(api.util.getRunningQueriesThunk()))

getMiddlewareState​

Signature​

getMiddlewareState(): ThunkWithReturnValue<ApiMiddlewareState | undefined>

interface ApiMiddlewareState {
getSubscriptionCount(queryCacheKey: string): number
}

Description​

A thunk that (if dispatched) returns read-only access to the state the API's middleware keeps for that store, such as subscription counts. This is separate from the API's slice in the Redux state, and is not visible through getState(). It returns undefined if the API's middleware has not been added to the store. Dispatching it never creates any state.

  • getSubscriptionCount(queryCacheKey) returns the number of active subscriptions to a query cache entry. It reads the current value on every call.

To check whether one specific initiate() call is still subscribed, use isSubscribed() on the result of initiate() instead.

Example​

Checking subscriptions inside baseQuery
const baseQuery: BaseQueryFn = async (args, api) => {
const middlewareState = api.dispatch(myApi.util.getMiddlewareState())
const isSubscribed =
(middlewareState?.getSubscriptionCount(api.queryCacheKey!) ?? 0) > 0
// ...
}

getRunningQueryThunk and getRunningMutationThunk​

Signature​

getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(
endpointName: EndpointName,
args: QueryArgFrom<Definitions[EndpointName]>
): ThunkWithReturnValue<
| QueryActionCreatorResult<
Definitions[EndpointName] & { type: 'query' }
>
| undefined
>

getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
endpointName: EndpointName,
fixedCacheKeyOrRequestId: string
): ThunkWithReturnValue<
| MutationActionCreatorResult<
Definitions[EndpointName] & { type: 'mutation' }
>
| undefined
>

Description​

Thunks that (if dispatched) return a single running query (or mutation) for a given endpoint name + argument (or requestId/fixedCacheKey) combination, if it is currently running. If it is not currently running, the function returns undefined.

These thunks are primarily added to add experimental support for suspense in the future. They enable writing custom hooks that look up if RTK Query has already got a running query/mutation for a certain endpoint/argument combination, and retrieving that to throw it as a promise.