It's time to ditch Medium for good! 🌈⚡️

Introducing Devblog by Hashnode. Blog on your domain for FREE. Highly customizable and optimized for developers.

Learn more

Cache Axios

Axios is a Promise based HTTP client: github.com/axios/axios

I would like to implement a cache control for GET requests. So that I don't query the same URL twice during a page load. That would be a cache that works for 10-20 seconds.

I would like to implement it as transparent as possible. Right now I call Axios by window.axios.get(url).then(response => {}) and the best would be to override the .get() method to inject the cache system.

Write your answer…

I wrote a cache system once, which works like this:

  1. Start by calculating a hash from all arguments which are important for the request, so that you only cache same requests and not slightly differing ones, which would lead to problems.
  2. Check your cache (a simple Map should work) if it contains the result data and when the call was made (timestamp)
  3. If not, check a second Map, which buffers in-transit request Promises
  4. If there is no entry, make the actual call. In any case, create a Promise and store an array with the next item containing refs to the Promise's resolve and reject methods.
  5. Once the call finishes, resolve (or reject) all Promises by calling the correct method from the buffer Map.
  6. Last but not least, store the result in the cache Map together with a timestamp.

Hashing the parameters should be simple, if you JSON-stringify them and then use something like this for the hash:

// https://stackoverflow.com/a/34842797
const hash = str => str.split('').reduce((prevHash, currVal) =>
    (((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
Show all replies

Of course this introduces the possibility of errors if wanting to load the same list twice (after modifications).

Either I will delete the cache after a few seconds or there should be a option to force load.


Of course config can be used to include a unique ID

Reply to this…