2024-02-22 14:37:08 +01:00
|
|
|
import { useSWRConfig } from 'swr';
|
|
|
|
|
2024-06-28 09:44:35 +02:00
|
|
|
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));
|
|
|
|
};
|
|
|
|
|
2024-02-22 14:37:08 +01:00
|
|
|
/**
|
|
|
|
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`
|
|
|
|
*/
|
2024-06-28 09:44:35 +02:00
|
|
|
export const useClearSWRCache = (
|
|
|
|
currentKey: string,
|
|
|
|
clearPrefix: string,
|
|
|
|
SWR_CACHE_SIZE = 1,
|
|
|
|
) => {
|
2024-02-22 14:37:08 +01:00
|
|
|
const { cache } = useSWRConfig();
|
2024-06-28 09:44:35 +02:00
|
|
|
clearCacheEntries(cache, currentKey, clearPrefix, SWR_CACHE_SIZE);
|
2024-02-22 14:37:08 +01:00
|
|
|
};
|