Skip to content

Commit

Permalink
feat: add CancelToken and isCancel to axios instance (#292)
Browse files Browse the repository at this point in the history
  • Loading branch information
3b3ziz authored and pi0 committed Oct 23, 2019
1 parent 170e399 commit b9335b1
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
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 @@ -184,6 +184,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

1 comment on commit b9335b1

@SaulIO
Copy link

@SaulIO SaulIO commented on b9335b1 Oct 24, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome

Please sign in to comment.