Skip to content

Instantly share code, notes, and snippets.

@FMCorz
Last active August 4, 2022 10:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save FMCorz/540bdd3e740d69dbf84fa0dc17cea940 to your computer and use it in GitHub Desktop.
Save FMCorz/540bdd3e740d69dbf84fa0dc17cea940 to your computer and use it in GitHub Desktop.
Fallback on cache when Axios reports a network error
import Axios from 'axios';
import { setupCache } from 'axios-cache-adapter';
import exclude from 'axios-cache-adapter/src/exclude';
// Define the cache adapter.
const cacheAdapter = setupCache({
clearOnStale: false,
});
const getKey = cacheAdapter.config.key;
const cacheStore = cacheAdapter.store;
// Our adapter factory which handles network errors.
const myAdapter = function(adapter) {
return async function(req) {
const isExcluded = exclude(cacheAdapter.config, req);
let res;
try {
res = await adapter(req);
} catch (e) {
if (e.request && (req.cache && req.cache.useOnNetworkError) && !isExcluded) {
// Mimic the behaviour of axios-cache-adapter, but directly get from store.
res = await cacheStore.getItem(getKey(req));
if (res && res.data) {
res = res.data;
res.config = req;
res.request = {
networkError: true,
fromCache: true
};
return res;
}
}
throw e;
}
return res;
};
};
const axios = Axios.create({
adapter: myAdapter(cacheAdapter.adapter),
cache: {
useOnNetworkError: true
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment