Caching with RTK Query
Illustrate how to configure cache settings in RTK Query for an API call by setting up customized cache lifetimes and invalidation methods.
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const api = createApi({
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getExampleData: builder.query({
query: () => '/example',
// Providing the time in seconds that a cache entry will be considered valid
keepUnusedDataFor: 60,
// Configuring cache invalidation
onCacheEntryAdded: async (
id,
{ cacheDataLoaded, cacheEntryRemoved, updateCachedData }
) => {
// wait for the initial query to resolve
await cacheDataLoaded;
// the cache entry has been added to the store
// you can perform additional tasks here, such as setting
// up timers or listening to external events
// when cache entry is about to be removed,
// you can perform cleanup tasks
await cacheEntryRemoved;
clearTimeout(myTimeoutId);
}
}),
}),
// Configure the invalidation behavior
invalidationBehavior: 'delayed',
});
This configures an RTK Query API with a single endpoint for fetching example data. It sets a cache lifetime with 'keepUnusedDataFor', defining the time in seconds that the cache is valid. The 'onCacheEntryAdded' lifecycle event allows performing additional side effects when a cache entry is added and managing cleanup before it's removed. The 'invalidationBehavior' is set to 'delayed' to coalesce invalidations, which improves performance by batching updates.