navi
This commit is contained in:
24
src/utils/fetchWIthCache.js
Normal file
24
src/utils/fetchWIthCache.js
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user