Skip to content
Advertisement

How to cancel token using a custom Axios instance?

I have an custom Axios instance using axios.create(). I would like to use the cancellation feature of Axios but the request fired from custom instance never gets cancelled. It does’t get detected in the .isCancel() method. But it works fine when used with the global Axios object.

const axiosAuth = axios.create();

const cancelToken = axios.CancelToken.source();

//request
const getProducts = async () => {
    try {
        const response = await axiosAuth.get('api', {
            cancelToken: cancelToken.token
        });
        if (response.status === 200) {
            return response.data;
        }
    } catch (err) {
        if (axios.isCancel(err)) {
            console.log('Error: ', err.message);
            return true;
        } else {
            throw new Error(err);
        }
    }
};
// I'm cancelling the request on button click using `cancelToken.cancel()`

I don’t understand why cancellation doesn’t work with a custom Axios instance.

Advertisement

Answer

Figured it out there was an issue in the one the Interceptors. Just make sure you check if its cancellation error there as well using Axios.isCancel() before you do anything with the error object.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement