Skip to content

feat: add CancelToken and isCancel to axios instance #292

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

Merged
merged 6 commits into from
Oct 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,53 @@ methods: {
}
}
```

### Cancel token

You can cancel a request using a _cancel token_.

> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).

You can create a cancel token using the `CancelToken.source` factory as shown below:

```js
const source = this.$axios.CancelToken.source()

this.$axios.$get('/user/12345', {
cancelToken: source.token
}).catch(error => {
if (this.$axios.isCancel(error)) {
console.log('Request canceled', error)
} else {
// handle error
}
})

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

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.')
```

You can also create a cancel token by passing an executor function to the `CancelToken` constructor:

```js
const { CancelToken } = this.$axios
let cancel

this.$axios.$get('/user/12345', {
cancelToken: new CancelToken(c => {
// An executor function receives a cancel function as a parameter
cancel = c
}),
})

// cancel the request
cancel()
```

> Note: you can cancel several requests with the same cancel token.
2 changes: 2 additions & 0 deletions lib/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,8 @@ export default (ctx, inject) => {

// Create new axios instance
const axios = Axios.create(axiosOptions)
axios.CancelToken = Axios.CancelToken
axios.isCancel = Axios.isCancel

// Extend axios proto
extendAxiosInstance(axios)
Expand Down