reactJS how to stop it listening to ajax request

后端 未结 2 1974
深忆病人
深忆病人 2021-01-07 09:22

I have ajax call in componentdidmount. And and then setState inside the ajax promise.

The code is like this

componentDidMount(){
    axios.post(\'myd         


        
2条回答
  •  醉话见心
    2021-01-07 10:08

    I have find a great solution that has been defined by istarkov

    const makeCancelable = (promise) => {
      let hasCanceled_ = false;
    
      const wrappedPromise = new Promise((resolve, reject) => {
        promise.then((val) =>
          hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
        );
        promise.catch((error) =>
          hasCanceled_ ? reject({isCanceled: true}) : reject(error)
        );
      });
    
      return {
        promise: wrappedPromise,
        cancel() {
          hasCanceled_ = true;
        },
      };
    };
    

    How to use:

    const somePromise = new Promise(r => setTimeout(r, 1000));
    
    const cancelable = makeCancelable(somePromise);
    
    cancelable
      .promise
      .then(() => console.log('resolved'))
      .catch(({isCanceled, ...error}) => console.log('isCanceled', isCanceled));
    
    // Cancel promise
    cancelable.cancel();
    

    the solution has been found there.

    My implementation.

    Inside my function

    const promiseShareByEmail = makeCancelable(this.props.requestShareByEmail(obj.email, obj.url));
    
                promiseShareByEmail.promise.then(response => {
                    const res = response.data;
    
                    if (res.code != 0)
                        throw new Error(res.message);
                    this.setState({
                        message: {
                            text: TextMeasurements.en.common.success_share_test,
                            code: Constants.ALERT_CODE_SUCCESS
                        }
                    });
                }).catch(err => {
                    if (err.isCanceled)
                        return;
    
                    this.setState({
                        message: {
                            text: err.message,
                            code: Constants.ALERT_CODE_ERROR
                        }
                    })
                });
    
                this.promiseShareByEmail = promiseShareByEmail;
    

    this.props.requestShareByEmail(obj.email, obj.url) that function returns promise from axios.

    when component will unmount cancel function should be invoked.

    componentWillUnmount() {
            this.promiseShareByEmail.cancel();
        }
    

    enjoy.

提交回复
热议问题