I have multiple component with axios plugin for some get requests. i need some help to cancel all xhr request with axios on component unmount event in react js. but the axios cancel code is not working. its return me cancel() is not a function error.
Code example:-
import axios from 'axios';
var CancelToken = axios.CancelToken;
var cancel;
axios.get('abc/xyz', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
Please help me to implement cancel request in axios.
Thanks.
Auto cancel the request when component unmounts. Let’s fix the problem by changing our code to auto cancel the Axios request when our component unmounts. Inside the useEffect function we now first grab a CancelToken Source from Axios and store it in a constant named source. We can use this to get a CancelToken and actually cancel the request.
To start the process of cancelling an axios request, the following steps are involved: Inside the axios request config, pass the token of the created source variable as the value of the cancelToken key/property.
The cleanup function can be used to dispose off the subscription. Once the request is cancelled, it is also required to check whether the reason for the failed request is the Abort or did it actually fail. When using AbortControlled, if a request is aborted, the error.name property will be “ AbortError ” In Axios we need to generate a Cancel Token.
You can cancel a request using a cancel token. The axios cancel token API is based on the withdrawn cancelable promises proposal. You can create a cancel token using the CancelToken.source factory as shown below: const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).
It is quite simple. Create the request in componentDidMount
and cancel it in componentWillUnmount
. Replace the url with an existing JSON file and this snippet will work as expected:
class MyComponent extends Component {
constructor (props) {
super(props)
this.state = {
data: []
}
}
componentDidMount () {
this.axiosCancelSource = axios.CancelToken.source()
axios
.get('data.json', { cancelToken: this.axiosCancelSource.token })
.then(response => {
this.setState({
data: response.data.posts
})
})
.catch(err => console.log(err))
}
componentWillUnmount () {
this.axiosCancelSource.cancel('Axios request canceled.')
}
render () {
const { data } = this.state
return (
<div>
{data.items.map((item, i) => {
return <div>{item.name}</div>
})}
</div>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With