Bug: Error: setupCache() should be called only once
martingrondein-nls opened this issue · comments
What happened?
I cannot get axios-cache-interceptor package to run. I get the following error:
Error: setupCache() should be called only once
is returned when
I cannot find anything in the docs about this issue or error. Any help would be greatly appreciated.
Here is my source code from apiHelper.tsx
:
import Axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
const axios = setupCache(Axios);
axios.defaults.baseURL = process.env.STRAPI_URL;
axios.defaults.headers.common['Authorization'] = 'Bearer ' + process.env.STRAPI_BEARER;
axios.defaults.headers.post['Content-Type'] = 'application/json';
const fetchResponse = async (path) => {
const url = `/api/${path}`;
const res = await axios.get(url);
return res.data;
};
export default fetchResponse;
axios-cache-interceptor version
1.3.2
Node / Browser Version
18.17.0
Axios Version
1.6.1
What storage is being used
Memory Storage
Relevant debugging log output
⨯ Error: setupCache() should be called only once
For any future folk that have the same issue and find this, I was able to overcome this by using:
const axios: AxiosInstance = Axios ? Axios : setupCache(Axios);
rather than
const axios = setupCache(Axios);
Hey @martingrondein-nls, the error explains itself, somehow in your environment, you are calling the const axios = setupCache(Axios);
line twice.
I recommend against applying this interceptor into the global Axios instance, but if you really need the need it, please register as shown below:
import type { AxiosCacheInstance } from 'axios-cache-interceptor';
const instance = Axios.defaults.cache ? Axios as AxiosCacheInstance : setupCache(Axios);
Or somehow avoid double calling setupCache
with another method inside your codebase, like singletons or any other pattern.