Axios allows you to cache responses by adding an adapter to your configuration. You can use a library like axios-cache-adapter
to cache responses using Axios in Typescript. Here's an example:
index.ts517 chars23 lines
The code above creates an Axios instance with a cached adapter from axios-cache-adapter
. The cache.adapter
is then added as the adapter to the Axios instance. This allows all requests made through this instance to be cached.
The api
instance then adds an interceptor to include a __cacheKey
parameter in the request URL to differentiate between multiple requests with the same URL but different parameters. This allows Axios to cache the responses separately for each request.
With this setup, you can simply use the api
instance to make requests, and Axios will cache responses automatically. For example:
index.ts115 chars5 lines
This example uses the api
instance to make a GET
request to /users
. The response is automatically cached by Axios and subsequent requests to the same endpoint will return the cached response if it's still valid.
Note that caching can have unintended consequences, like showing stale data or users experiencing different data when hitting the same endpoint with different query parameters. You should use caching cautiously and only where it makes sense.
gistlibby LogSnag