DEV Community

Discussion on: Cache API in JavaScript - with just 20 lines of code.

Collapse
 
piixiiees profile image
Jose Gascon • Edited

Nice post, thanks for sharing.
What do you think about integrating the clearing of the cache in the getData function?
Performance wise it should be very similar and the result is even more compact (just 10 lines 😄)

const cache = {};

async function getData(url){
  const currentTime = new Date();
  if(cache[url] !== undefined) {
    if((currentTime - cache[url].time) < 10000) return cache[url].value;
    delete cache[url];
  }
  await fetch(url)
    .then(response => response.json())
    .then(json => cache[url] = {time: currentTime, value: json});
  return cache[url].value;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rajeshroyal profile image
Rajesh Royal

➕➕