With classic rest API, there are several strategies to deal with caching.
1) You can have a REST API providing a cache-Control in its HTTP headers to help the browser to minimize server round-trips when possible (an interested link on the subject). It's a good one since few to no work is required on the front-end side.
2) You can have a reverse proxy on your back-end to filter incoming requests and use cache when possible. You do not save bandwidth but at least, you release the server's load.
3) However, if you are not in charge of the API but you still want to have a caching method, a naive way of doing it is to use memoization. Just a big word to describe a function that can save the results of its computation. Therefore, if it's called twice with the same arguments, the second call costs no compute time.
Let's say you use axios to query whatever API you want with an id as an argument (mind that it's kind of a pseudo code - it won't run as is) :
functionrequest(){// our cache is a simple// object hereletcache={};returnasyncfunction(id){//if the cache has an "id" value// one returns it immediatelyif(cache[id]){returncache[id]}//the actual query//to the serverconstresults=awaitaxios.get(`${MY_API_URL}/${id}`);//one caches the value for future usescache[id]=results;returnresults;}}
Obviously, it's a veryveryvery naive implementation which would require additional work to deal with expire dates, invalidation of the cache if a mutation is sent to the server for instance and so on. But I hope you'll get the idea of how the subject could be tackled :)
With classic rest API, there are several strategies to deal with caching.
1) You can have a REST API providing a
cache-Control
in its HTTP headers to help the browser to minimize server round-trips when possible (an interested link on the subject). It's a good one since few to no work is required on the front-end side.2) You can have a reverse proxy on your back-end to filter incoming requests and use cache when possible. You do not save bandwidth but at least, you release the server's load.
3) However, if you are not in charge of the API but you still want to have a caching method, a naive way of doing it is to use
memoization
. Just a big word to describe afunction
that can save the results of its computation. Therefore, if it's called twice with the same arguments, the second call costs no compute time.You can achieve this using closure in
javascript
.Let's say you use axios to query whatever API you want with an
id
as an argument (mind that it's kind of a pseudo code - it won't run as is) :Obviously, it's a very very very naive implementation which would require additional work to deal with expire dates, invalidation of the cache if a mutation is sent to the server for instance and so on. But I hope you'll get the idea of how the subject could be tackled :)
I definitely do. This has sure come in handy, and just cycling back to say thank you.
long shot but react-query is the go-to now ;)