Cache API in JavaScript - with just 20 lines of code.
Rajesh Royal
Posted on May 15, 2022
let cache = {};
async function getData(url){
let result = "";
if(cache[url] !== undefined) return cache[url].value;
await fetch(url)
.then(response => response.json())
.then(json => cache[url] = {time: new Date(), value: json});
return cache[url].value;
}
// Interval to clear cache;
setInterval(function (){
if(Object.keys(cache).length > 0){
let currentTime = new Date();
Object.keys(cache).forEach(key => {
let seconds = currentTime - cache[key].time;
if(seconds > 10000){
delete cache[key];
console.log(`${key}'s cache deleted`)
}
})
}
}, 3000);
Now you can call your API's like this.
getData("https://jsonplaceholder.typicode.com/todos/1")
.then(data => console.log(data));
If there is a cache value of the current api call then it will return values from cache otherwise call the api and return data while adding the response to cache.
Preview
I'm assuming this is much better than RTK Query and React Query 😅.
💖 💪 🙅 🚩
Rajesh Royal
Posted on May 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.