Code Monkey home page Code Monkey logo

Comments (7)

SamueleCaprioli97 avatar SamueleCaprioli97 commented on July 28, 2024 3

Hi @arthurfiorette, thank you for spending time on this issue.
Here, i've tried to update my axios dependency to 1.0.0-alpha.1 which includes your commits, but i've encountered the same behavior.

I think it's related to this portion of code in Axios:
https://github.com/axios/axios/blob/3cf6ad72033fd6eacf720a7d700f99dc96f586a3/lib/core/dispatchRequest.js#L10-L31

When a request is aborted before it is crafted, the throwIfCancellationRequested function will not pass the config as parameter to CanceledError


Anyway i found a temporary workaround for handling aborted request that makes me able to go ahead:

import axios from 'axios'
import { setupCache, buildMemoryStorage, defaultKeyGenerator } from 'axios-cache-interceptor'
const MINUTE = 1000 * 60
const memoryStorage = buildMemoryStorage()
const instance = setupCache(axios, {
  methods: ['get', 'options'],
  ttl: MINUTE,
  storage: memoryStorage
})
instance.interceptors.request.use(function (config) {
  if (!config.cache) {
    return config
  }
  let aborted = false
  if (config.cancelToken) {
    if (axios.isCancel(config.cancelToken.reason)) {
      aborted = true
    } else {
      config.cancelToken.subscribe(() => {
        abortCacheHandler(config)
      })
    }
  }
  if (config.signal) {
    if (config.signal.aborted) {
      aborted = true
    } else {
      config.signal.addEventListener('abort', () => abortCacheHandler(config), { once: true })
    }
  }
  if (aborted) {
    return { ...config, ...{ cache: false } }
  }
  return config
})
function abortCacheHandler (config) {
  const requestKey = defaultKeyGenerator(config)
  memoryStorage.get(requestKey, config).then(request => {
    if (request.state !== 'cached') {
      memoryStorage.remove(requestKey, config)
    }
  })
}

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024 2

Hey, thanks for your bug report.

I can't look into it this weekend, I'll try to fix it somewhere between Monday and next weekend...

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024 1

Hey @SamueleCaprioli97. I will close this issue as it is not related to something axios-cache-interceptor can do to fix it.

I polished the above code into a more suitable one, you can use it:

import Axios from 'axios';
import { setupCache } from './cache/create';

const axios = setupCache(Axios.create());

axios.interceptors.request.use((config) => {
  if (!config.cache) {
    return config;
  }

  async function reject() {
    const key = config.id ?? axios.generateKey(config);

    const storage = await axios.storage.get(key, config);

    // Request cancelled but response is already cached
    if (storage.state === 'cached' || storage.state === 'stale') {
      return;
    }

    await axios.storage.remove(key, config);
  }

  if (config.signal) {
    // Already cancelled request
    if (config.signal.aborted) {
      config.cache = false;
      return config;
    }

    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    config.signal.addEventListener('abort', reject);
  }

  // NOTE: Cancel token is DEPRECATED but are here for backward compatibility
  // you can remove this block if you don't use cancel token.
  // https://axios-http.com/docs/cancellation
  if (config.cancelToken) {
    // Already cancelled request
    if (Axios.isCancel(config.cancelToken.reason)) {
      config.cache = false;
      return config;
    }

    void config.cancelToken.promise.then(reject);
  }

  return config;
});

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024 1

Hey @SamueleCaprioli97, I reopened this PR because axios just released v1.0.0.
I added this fix to be in our roadmap :)

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024 1

Fixed! Going live with v1.0.0

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024

Hey @SamueleCaprioli97, i have some bad news (for now)...

Looking closely, this was the same error I got when building an axios cache interceptor react hooks library (axios-cache-hooks).

Let me explain it:

When a request throws any error, the response interceptor executes the onRejected response interceptor function, instead of the onResolved:

const onRejected: ResponseInterceptor['onRejected'] = async (error) => {
const config = error.config as CacheRequestConfig;

And these functions are stateless, so the only thing that guides us on each request it the provided error parameter. The problem is, when the error is from a cancelled request, axios does not returns any other information.

(this is everything available at line 204)
image

Coming back to axios-cache-hooks, I've detected it some time ago with the automatically cancellation mechanism and pushed a PR to axios that fixed it, axios/axios#4659.

The problem is that v0.27.2 seems to be our last version before 1.X, that's why it never actually got released into a new patch version (and why axios-cache-hooks is frozen in the time).

Our current hope is to get jasonsaayman to cherry pick this PR into a v0 patch release. When the patch gets released, automagically this problem will be fixed, so, no need to a new axios-cache-interceptor version.

P.S.: Thanks for helping this package :)

Edit: Look at axios/axios#4659 (comment)

from axios-cache-interceptor.

arthurfiorette avatar arthurfiorette commented on July 28, 2024

Waiting for axios/axios#4922

from axios-cache-interceptor.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.