Created
May 29, 2018 15:24
-
-
Save ducdigital/1d77f4b8d7e20401265e04b2f567176f to your computer and use it in GitHub Desktop.
Sample of React component that allow cancel axios ajax call when unmount
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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