Skip to content

Instantly share code, notes, and snippets.

@box-turtle
Forked from adeelibr/Abort Controller In Axios
Created January 16, 2019 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save box-turtle/6bba78539956fd877846bcbbd6fe7d15 to your computer and use it in GitHub Desktop.
Save box-turtle/6bba78539956fd877846bcbbd6fe7d15 to your computer and use it in GitHub Desktop.
Abort Controllers In Axios
import React, { Component } from 'react';
import axios from 'axios';
class Example extends Component {
signal = axios.CancelToken.source();
state = {
isLoading: false,
user: {},
}
componentDidMount() {
this.onLoadUser();
}
componentWillUnmount() {
this.signal.cancel('Api is being canceled');
}
onLoadUser = async () => {
try {
this.setState({ isLoading: true });
const response = await axios.get('https://randomuser.me/api/', {
cancelToken: this.signal.token,
})
this.setState({ user: response.data, isLoading: true });
} catch (err) {
if (axios.isCancel(err)) {
console.log('Error: ', err.message); // => prints: Api is being canceled
} else {
this.setState({ isLoading: false });
}
}
}
render() {
return (
<div>
<pre>{JSON.stringify(this.state.user, null, 2)}</pre>
</div>
)
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment