Skip to content

Instantly share code, notes, and snippets.

@ducdigital
Created May 29, 2018 15:24
Show Gist options
  • Save ducdigital/1d77f4b8d7e20401265e04b2f567176f to your computer and use it in GitHub Desktop.
Save ducdigital/1d77f4b8d7e20401265e04b2f567176f to your computer and use it in GitHub Desktop.
Sample of React component that allow cancel axios ajax call when unmount
class SampleCancellableAjax extends Component {
constructor(props) {
super(props);
/* Ajax handlers */
this._cancelToken = CancelToken.source();
}
componentDidUpdate() {
const { input } = this.props;
axiosAjaxCall(
{ input },
this._cancelToken.token,
).then(({data}) => {
this.setState({
data,
});
});
}
componentWillUnmount() {
if (this._cancelToken) {
this._cancelToken.cancel('Operation canceled by the user.');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment