import React from 'react';

const cancelPromise = (WrappedComponent) =>
    class extends React.Component {
        state = {
            cancelled: false
        };

        constructor(props) {
            super(props);
            this.cancelPromise = this.cancelPromise.bind(this);
        }

        componentWillUnmount() {
            this.setState({cancelled: true});
        }

        cancelPromise(promise) {
            return new Promise((resolve, reject) => {
                promise.then((...data) => {
                    if(this.state.cancelled) {
                        reject({cancelled: true});
                    } else {
                        resolve(...data);
                    }
                }).catch((...error) => {
                    reject(...error);
                });
            });
        }

        render() {
            return (
                <WrappedComponent {...this.props} cancelPromise={this.cancelPromise}/>
            );
        };
    };

export {cancelPromise};