Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abort all Axios requests when change route use vue-router

how can i abort / cancel Axios request before complete when i change route use vue-router.

when user open page it automatically send axios request to get some data, but user don't waiting to get response then he is changing route by vue-router it will be a lot of Axios requests

so is there any solve to my problem

like image 423
Ghyath Darwish Avatar asked Jul 20 '18 09:07

Ghyath Darwish


1 Answers

Basically you have to generate a global cancel token

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

and use it in all your requests by passing it in the config parameter

GET request:

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

POST request:

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

Then, within a vue-router beforeEach navigation guard you can cancel all requests using:

source.cancel('Operation canceled by the user.');

Here's the official axios guide for cancellation: https://github.com/axios/axios#cancellation

like image 50
Fab Avatar answered Oct 15 '22 07:10

Fab