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

rajeshroyal

Rajesh Royal

Posted on May 15, 2022

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


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);


Enter fullscreen mode Exit fullscreen mode

Now you can call your API's like this.



getData("https://jsonplaceholder.typicode.com/todos/1")
.then(data => console.log(data));


Enter fullscreen mode Exit fullscreen mode

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

Image Cache API in JavaScript - with just 20 lines of code

I'm assuming this is much better than RTK Query and React Query 😅.

💖 💪 🙅 🚩
rajeshroyal
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.

Related