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

let cache = {};
async operate getData(url){
    let end result = "";
    if(cache[url] !== undefined) return cache[url].worth;

    await fetch(url)
    .then(response => response.json())
    .then(json => cache[url] = {time: new Date(), worth: json});

    return cache[url].worth;
}

// Interval to clear cache;
setInterval(operate (){
    if(Object.keys(cache).size > 0){
        Object.keys(cache).forEach(key => {
            let currentTime = new Date();
            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 may name your API’s like this.

getData("https://jsonplaceholder.typicode.com/todos/1")
.then(information => console.log(information));
Enter fullscreen mode

Exit fullscreen mode

If there’s a cache worth of the present api name then it should return values from cache in any other case name the api and return information whereas including the response to cache.



Preview

I am assuming that is significantly better than RTK Question and React Question 😅.

Add a Comment

Your email address will not be published. Required fields are marked *