Refresh Token
These are included as api.util
inside the API object.
api.util
In RTK Query (Redux Toolkit Query), api.util
refers to a set of utilities that can be used for caching and optimistic updates within the API service. It's an important feature when working with Redux Toolkit and RTK Query because it allows you to interact with the cache, trigger refetches, and update the store, making it easier to manage the state of your app with API calls.
Here’s a breakdown of api.util
:
-
api.util.updateQueryData
This method allows you to optimistically update the data in the Redux store for a particular query. It is useful when you want to modify or update the data in the cache without making an actual API call (e.g., when performing optimistic updates).
api.util.updateQueryData("getPosts", undefined, (draft) => { draft.push(newPost); // Add a new post to the cached data });
'getPosts'
is the name of the query endpoint.undefined
is used when the query does not take any parameters.- The
draft
is the mutable data of the query that you can update.
-
api.util.invalidateTags
This utility helps you invalidate the cache for specific tags, triggering a refetch of the relevant data. It's typically used when you want to refresh certain data after a mutation (e.g., after a successful update, delete, or create operation).
- This invalidates a cache entry for a
Post
with the givenid
. - This triggers a refetch for the specific
Post
if it’s being used in a component.
- This invalidates a cache entry for a
-
api.util.resetApiState
This method is used to reset the entire API state in the Redux store. It can be useful when you want to clear all cached data, for example, when the user logs out.
-
api.util.select()
,api.util.selectQueryData()
These methods help you select specific data from the API cache, allowing you to access and inspect cached data directly from the Redux store.
When to Use api.util:
- Optimistic updates: When you want to make an update to the cache before the mutation request finishes (e.g., showing an updated list of posts right after creating a new one).
- Cache invalidation: To ensure that the cache is updated and that the next time a query is made, the data is fresh (e.g., after a successful mutation).
- Clearing cache: When resetting the application state (like when logging out).
- Refetching data: After performing certain actions like adding, updating, or deleting items, it may be necessary to refresh the associated data to reflect those changes.
Example Scenario:
Suppose you have a getPosts
query and a createPost
mutation. When you create a new post, you may want to optimistically add the post to the cache without waiting for the API request to finish. Then, after the mutation finishes, you can invalidate the cache for getPosts
to make sure the list is refreshed.
const postsApi = createApi({
reducerPath: "postsApi",
baseQuery: fetchBaseQuery({ baseUrl: "/api/" }),
endpoints: (builder) => ({
getPosts: builder.query({
query: () => "posts",
providesTags: (result) =>
result ? [...result.map(({ id }) => ({ type: "Post", id }))] : [],
}),
createPost: builder.mutation({
query: (newPost) => ({
url: "posts",
method: "POST",
body: newPost,
}),
// Optimistically update the cache
onQueryStarted: async (newPost, { dispatch, queryFulfilled }) => {
// Optimistically update the cache
dispatch(
postsApi.util.updateQueryData("getPosts", undefined, (draft) => {
draft.push(newPost); // Add the new post optimistically
})
);
try {
await queryFulfilled;
} catch (err) {
// Handle error if needed
}
},
// Invalidate cache after mutation
onSuccess: () => {
dispatch(postsApi.util.invalidateTags([{ type: "Post" }]));
},
}),
}),
});
In the above example:
onQueryStarted
is used to optimistically update thegetPosts
cache before the mutation completes.onSuccess
invalidates the cache to ensure the data is fresh after the mutation.
Conclusion
api.util
in RTK Query is a powerful tool that gives you control over how you interact with your API's cache and manage refetching, updating, and invalidating data in a Redux store. It simplifies common tasks like handling optimistic updates, cache invalidation, and direct data updates, making it easier to keep your app's state in sync with the server.
API Slices: React Hooks
RTK Query provides additional hooks for more advanced use-cases, although not all are generated directly on the Api object as well. The full list of hooks generated in the React-specific version of createApi
is as follows:
useQuery
(endpoint-specific, also generated on the Api object)useMutation
(endpoint-specific, also generated on the Api object)useQueryState
(endpoint-specific)useQuerySubscription
(endpoint-specific)useLazyQuery
(endpoint-specific, also generated on the Api object)useLazyQuerySubscription
(endpoint-specific)usePrefetch
(endpoint-agnostic)