JavaScript Fetch with Caching
Implement a cached fetch wrapper in vanilla JavaScript using the Cache API with stale-while-revalidate strategy, request deduplication, and automatic cache.
Code
const cache = new Map();
const pending = new Map();
export async function cachedFetch(url, { ttl = 60000 } = {}) {
const entry = cache.get(url);
if (entry && Date.now() - entry.time < ttl) {
return entry.data;
}
if (entry && Date.now() - entry.time < ttl * 2) {
if (!pending.has(url)) {
pending.set(url, fetch(url).then(r => r.json()).then(d => {
cache.set(url, { data: d, time: Date.now() });
pending.delete(url);
}));
}
return entry.data;
}
const data = await (await fetch(url)).json();
cache.set(url, { data, time: Date.now() });
return data;
}