Medium
You're building a caching system for API responses. What's wrong with this implementation of a memoized fetch wrapper?
1<p>const createApiCache = () => {</p><p> const cache = new Map();</p><p> </p><p> return async function fetchWithCache(url, options = {}) {</p><p> const cacheKey = <code>${url}-${JSON.stringify(options)}</code>;</p><p> </p><p> if (cache.has(cacheKey)) {</p><p> const { data, timestamp } = cache.get(cacheKey);</p><p> const age = Date.now() - timestamp;</p><p> </p><p> if (age < 5 <em> 60 </em> 1000) { // 5 minutes</p><p> return data;</p><p> }</p><p> }</p><p> </p><p> const response = await fetch(url, options);</p><p> const data = await response.json();</p><p> </p><p> cache.set(cacheKey, {</p><p> data,</p><p> timestamp: Date.now()</p><p> });</p><p> </p><p> return data;</p><p> };</p><p>};</p><p>const api = createApiCache();</p>