This commit is contained in:
h z
2024-12-03 09:41:58 +00:00
parent 8bbfc10a39
commit b355b867a5
8 changed files with 233 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
export async function fetchWithCache(url, cacheKey = url, cacheExpiry = 60) {
const cachedData = localStorage.getItem(cacheKey);
const now = Date.now();
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData);
if (now - timestamp < cacheExpiry * 1000) {
console.log("Cache hit for:", url);
return data;
} else {
console.log("Cache expired for:", url);
}
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: now }));
return data;
}