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 ๐ .
Latest comments (24)
Thanks, great read.
Cool!
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 ๐)
โโ
First rule of software development: see if it's been done before - don't reinvent the wheel. Check out the Cache interface, which would provide you with caching across browser sessions: developer.mozilla.org/en-US/docs/W...
Chill out man, Its just an experiment of curiosity which I felt good to share.
Nice post
Thanks @aaravrrrrrr
Note: if you need caching for production projects, I highly recommend searching for existing implementations (or at least existing algorithms).
Otherwise I have some notes:
cache[key].time
with a validUntil time object.restep++
Can I ask you why are you doing this:
Instead of this:
If you use await you can replace those .then and I think this is much more cleaner :D
Good Improvement. I will update the code.
I think you can append .json() to this:
(I didn't test it but I think it should work)
Happy to help you! :D
No it cannot be done.
Actually that doesn't work and you'll get an error.
Uncaught TypeError: fetch(...).json is not a function
Because
fetch()
return a promise, and it doesn't have ajson
method on it.It should be like this.
or this
Note that calling
response.json()
also return a promise so you need toawait
it to get the result.Great job. Thanks for sharing.
๐๐
What happen if you get the same data at the same url very closely, the first call didn't finished so you make two calls instead of one
Didn't understand much, can you please explain a bit more.
Nice idea to use Memoized results.Thanks!!