1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-28 00:06:53 +01:00
unleash.unleash/frontend/src/hooks/useClearSWRCache.ts
Jaanus Sellin 82a53fa9b3
feat: introduce large cache for swr (#7470)
Previously, clearing the SWR cache cleared all entries. Now you can
configure the cache size.

1. This makes the search more fluid. Previously, if you went back and
forth on pages, you were always sent to the loading state.
2. This also solves the issue where the command bar search cleared the
cache for all other searches.
3. Additionally, it addresses the problem where the global search
cleared the cache for project search.
2024-06-28 10:44:35 +03:00

34 lines
938 B
TypeScript

import { useSWRConfig } from 'swr';
type Cache = ReturnType<typeof useSWRConfig>['cache'];
export const clearCacheEntries = (
cache: Cache,
currentKey: string,
clearPrefix: string,
SWR_CACHE_SIZE = 1,
) => {
const keys = [...cache.keys()];
const filteredKeys = keys.filter(
(key) => key.startsWith(clearPrefix) && key !== currentKey,
);
const keysToDelete = filteredKeys.slice(SWR_CACHE_SIZE - 1);
keysToDelete.forEach((key) => cache.delete(key));
};
/**
With dynamic search and filter parameters we want to prevent cache from growing extensively.
We only keep the latest cache key `currentKey` and remove all other entries identified
by the `clearPrefix`
*/
export const useClearSWRCache = (
currentKey: string,
clearPrefix: string,
SWR_CACHE_SIZE = 1,
) => {
const { cache } = useSWRConfig();
clearCacheEntries(cache, currentKey, clearPrefix, SWR_CACHE_SIZE);
};