fix render issue

This commit is contained in:
h z
2024-12-03 16:36:32 +00:00
parent 22da3bc90d
commit 18a84123d3
8 changed files with 38 additions and 10 deletions

View File

@@ -0,0 +1,40 @@
const ongoingRequests = new Map();
export async function fetchWithCache(url, cacheKey = url, cacheExpiry = 60) {
if (ongoingRequests.has(url)) {
return ongoingRequests.get(url);
}
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);
}
}
try {
const fetchPromise = fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then((data) => {
localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: now }));
ongoingRequests.delete(url);
return data;
});
ongoingRequests.set(url, fetchPromise);
return await fetchPromise;
} catch (error) {
ongoingRequests.delete(url);
throw error;
}
}