Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibility to opt-in cache #511

Open
panghaoyuan opened this issue Feb 28, 2023 · 14 comments
Open

Possibility to opt-in cache #511

panghaoyuan opened this issue Feb 28, 2023 · 14 comments
Assignees
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed

Comments

@panghaoyuan
Copy link

panghaoyuan commented Feb 28, 2023

I have an old project of nextjs project.. Most of the pages of the project do not need caching. I only need to use this cache on a few pages. How to set the global setting to disable caching, I only need to enable caching on a few pages.
such as

axios.get('url', {
  cache: true,
});

or

axios.get('url', {
  cache: {
    open: true,
    ...otherOption
 },
});

how can i resolve this question

@panghaoyuan panghaoyuan added the bug Something isn't working label Feb 28, 2023
@arthurfiorette
Copy link
Owner

Hey @panghaoyuan, disabling cache by default seems to be a no-op to this package ship as a feature.

If the hassle is worth, you can use cache: false on every page that cache should be disabled and use axios as normally on every page that cache should be enabled. Which is the currently recommended and default behavior of axios-cache-interceptor.

To incrementally adopt axios-cache-interceptor in your current system, I'd export two axios instances in your code, like axios and newAxios with cache enabled.

Feel free to reopen this issue :)

@CatchABus
Copy link
Contributor

I have an old project of nextjs project.. Most of the pages of the project do not need caching. I only need to use this cache on a few pages. How to set the global setting to disable caching, I only need to enable caching on a few pages. such as

axios.get('url', {
  cache: true,
});

or

axios.get('url', {
  cache: {
    open: true,
    ...otherOption
 },
});

how can i resolve this question

You could also try axios defaults perhaps.

import axios from "axios";

axios.defaults.cache = false;

@seba9999
Copy link

seba9999 commented Mar 1, 2023

Just to leave a comment for anyone trying to achieve that and reaching here ... :

Adding axios.defaults.cache = false; alone won't work.
By doing this you are "deleting" the cache object needed by this lib ....

That's what I've done to "activate" the cache to only 1 route :

setupCache(axiosInstance);

// After beign setup we store that cache settings
const savedCacheSettings = axiosInstance.defaults.cache;

// This will disable cache for all requests
axiosInstance.defaults.cache = false;

// then export this to whatever service you would like 
export const cacheSettings = savedCacheSettings;

And in whateverServiceYouWouldLike.js :

import axiosInstance, { cacheSettings } from 'AxiosSetup.js';

export const getXXXXX = async () => {
  axiosInstance.defaults.cache = cacheSettings;
  const r = await axiosInstance.get('/getSomething');
  
  // turns back cache to false for next calls
  axiosInstance.defaults.cache = false;
  return r;
};

And seems to be working ;)

@MatthewPattell
Copy link

MatthewPattell commented Oct 26, 2023

An even simpler solution:

setupCache(axios, {
  // disable methods
  methods: [],
});

// For request with cache just add methods
const isCached = true;

const { data } = await axios.request({
  url: '/....',
  cache: {
          ...(isCached
            ? {
                methods: ['get'],
              }
            : {}),
        },
});

@CJY0208
Copy link

CJY0208 commented Aug 12, 2024

According to the source code, I am currently using the following code to completely disable the default cache in my project

import axios from 'axios'
import { setupCache, defaultRequestInterceptor, AxiosCacheInstance } from 'axios-cache-interceptor'

const getCacheRequestInterceptor = (axios: AxiosCacheInstance) => {
  const defaultRequestInterceptorResult = defaultRequestInterceptor(axios)
  const onFulfilled = ((config, ...args) => {
    if (!config?.cache || (config?.cache as any)?.ttl <= 0) {
      config.cache = false
    }

    return defaultRequestInterceptorResult.onFulfilled(config, ...args)
  }) as typeof defaultRequestInterceptorResult.onFulfilled
  const apply = (() => axios.interceptors.request.use(onFulfilled)) as typeof defaultRequestInterceptorResult.apply

  return {
    ...defaultRequestInterceptorResult,
    onFulfilled,
    apply,
  }
}

const rawAxiosInstance = axios.create()

const axiosInstance = setupCache(rawAxiosInstance, {
  ttl: -1,
  requestInterceptor: getCacheRequestInterceptor(rawAxiosInstance as AxiosCacheInstance),
})

export default axiosInstance

@CJY0208
Copy link

CJY0208 commented Aug 12, 2024

@arthurfiorette

Can I add the default cache disable feature to this project?

This is very necessary for projects that want to manually use cache

Like this

import Axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';

const instance = Axios.create(); 
const axios = setupCache(instance, {
  cache: false,
});

@sayhicoelho
Copy link

sayhicoelho commented Sep 20, 2024

Just to leave a comment for anyone trying to achieve that and reaching here ... :

Adding axios.defaults.cache = false; alone won't work. By doing this you are "deleting" the cache object needed by this lib ....

That's what I've done to "activate" the cache to only 1 route :

setupCache(axiosInstance);

// After beign setup we store that cache settings
const savedCacheSettings = axiosInstance.defaults.cache;

// This will disable cache for all requests
axiosInstance.defaults.cache = false;

// then export this to whatever service you would like 
export const cacheSettings = savedCacheSettings;

And in whateverServiceYouWouldLike.js :

import axiosInstance, { cacheSettings } from 'AxiosSetup.js';

export const getXXXXX = async () => {
  axiosInstance.defaults.cache = cacheSettings;
  const r = await axiosInstance.get('/getSomething');
  
  // turns back cache to false for next calls
  axiosInstance.defaults.cache = false;
  return r;
};

And seems to be working ;)

This may cause issues in your application if you have multiple requests running simultaneously with different cache configurations.

@sayhicoelho
Copy link

@arthurfiorette This is a needed feature since we don't want to have two axios instances in our applications. Disabling cache globally would be useful.

@arthurfiorette
Copy link
Owner

What's the problem with 2 axios instances?

@CatchABus
Copy link
Contributor

CatchABus commented Sep 20, 2024

@sayhicoelho You can try setting cache.override to true globally: https://axios-cache-interceptor.js.org/config/request-specifics#cache-override
Cache will still be enabled but will get overridden every time by a new response.

Although, I think having another axios instance for them would be ideal.

@arthurfiorette
Copy link
Owner

Cache will still be enabled but will get overridden every time by a new response.

Nice! I didn't think of that before. This is probably the best solution since once override: false, you already have a lot of populated data.

@mahnunchik
Copy link

@arthurfiorette

Can I add the default cache disable feature to this project?

This is very necessary for projects that want to manually use cache

Like this

import Axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';

const instance = Axios.create(); 
const axios = setupCache(instance, {
  cache: false,
});

@arthurfiorette I need exectly the same feature: disabled cache by default but with options specified.

@arthurfiorette
Copy link
Owner

It seems that a lot of people are wanting this feature, I'll reopen this issue in case someone wants to work on it.

remember to add unit tests :)

@arthurfiorette arthurfiorette added enhancement New feature or request help wanted Extra attention is needed good first issue Good for newcomers and removed bug Something isn't working labels Oct 18, 2024
@arthurfiorette arthurfiorette changed the title How to cache:false as a global configuration Possibility to opt-in cache Oct 18, 2024
@M-Matin-dev
Copy link

I think adding multiple instances of axios with distinct caching settings might be a possible workaround here. I don’t encounter any errors from running setupCache multiple times as long as I pass a different axios instance each time and this allows caching to be enabled only where needed, by using the cached instance.

Additionally, extracting other global logic into a function that accepts an axios instance simplifies applying other interceptors consistently across all instances.

Pseudo-code:

import { setupCache } from 'axios-cache-interceptor'

// Function to add authentication interceptors
function addAuthToAxiosInstance(instance) {
  instance.interceptors.request.use(config => { /* add token */ });
  instance.interceptors.response.use(response => response, error => { /* handle auth errors */ });
}

// Create axios instances with different caching settings
const globalAxios = axios.create({})
const inMemoryCachedAxios = setupCache(axios.create(), { /* in-memory cache config */ })
const persistentCachedAxios = setupCache(axios.create(), { /* persistent cache config */ })

// Apply auth logic to each instance
addAuthToAxiosInstance(globalAxios)
addAuthToAxiosInstance(inMemoryCachedAxios)
addAuthToAxiosInstance(persistentCachedAxios)

export { globalAxios, inMemoryCachedAxios, persistentCachedAxios }

This setup allows selective caching with minimal code changes and keeps the configuration for each API call flexible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

9 participants