Cancel a promise when a component is unmounted in ReactJS
A variation of this https://hshno.de/BJ46Xb_r7 seemed to work for me.I made an HOC with the mounted
instance variable and wrapped all async components in it.
Below is what my code roughly loks like.
export function makeMountAware(Component) { return class MountAwareComponent extends React.Component { mounted = false; componentDidMount() { this.mounted = true; } componentWillUnmount() { this.mounted = false; } return ( <Component mounted = {this.mounted} {...this.props} {...this.state} /> ); }}class AsyncComponent extends React.Component { componentDidMount() { fetchAsyncData() .then(data => { this.props.mounted && this.setState(prevState => ({ ...prevState, data })); }); }}export default makeMountAware(AsyncComponent);
You can't cancel native ES6 promises. Read more at https://medium.com/@benlesh/promise-cancellation-is-dead-long-live-promise-cancellation-c6601f1f5082
What you can do, however, is maybe use non-native promise libraries like Bluebird or Q, that give you promises that can be cancelled.
There are various things you can do. The simplest is to reject
the promise:
this.prom = new Promise((resolve, reject) => { this.rejectProm = reject; ...});
and then
componentWillUnmount(){ if (this.rejectProm) { this.rejectProm(); this.rejectProm = nil; } console.log("unmounted")}