Add a time-based cache for the progress result from the API
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
export function fetchWithCache<Type>(
|
||||
cacheKey: string,
|
||||
fetchFunction: () => Promise<Type>,
|
||||
maxAge: number = 5 // 30 seconds
|
||||
): Promise<Type> {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const cachedData = localStorage.getItem(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
const { data, timestamp } = JSON.parse(cachedData) as CacheEntry<Type>;
|
||||
const now = Date.now();
|
||||
const ageInSeconds = (now - timestamp) / 1000;
|
||||
|
||||
// Check if cache is still valid
|
||||
if (ageInSeconds < maxAge) {
|
||||
return resolve(data);
|
||||
}
|
||||
}
|
||||
|
||||
// Cache is missing or expired, fetch fresh data
|
||||
const freshData = await fetchFunction();
|
||||
const cacheEntry: CacheEntry<Type> = {
|
||||
data: freshData,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
localStorage.setItem(cacheKey, JSON.stringify(cacheEntry));
|
||||
resolve(freshData);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user