How can I undo the next "then" in a Promise when a React component is unmounted / reused?

I am trying to reverse a promise when a React component is unmounted / reused. Right now I am facing a problem that I can better explain in the small graph below:

** Promise should complete (make AJAX requests and update reductions store accordingly)

Component is created => Installed => _onClick () started => Promises to start => Component gets unmounted but is being reworked => Promised finished => calls setState () on the reworked component and rerenders with the wrong state from the previous component.

How can I cancel / interrupt / stop the next "then" but still deliver on the promise?

...
    _onClick() {
        let dispatch = this.props.dispatch;

        if (!this.state.on) {
            API.On(dispatch, this.props.id).then(() => {
                this.setState({
                    on: true,
                })
            }).catch((error) => {
                this.setState({
                    on: false,
                })
            });
        } else {
            API.Off(dispatch, this.props.id).then(() => {
                this.setState({
                    on: false,
                });
            }).catch((error) => {
                this.setState({
                    on: true,
                })
            })
        }
    }
...

      

+3


source to share


1 answer


What I'll do here is just adding a conditional to the body of the promise that sets the state. You can use React lifecycle hooks to keep track of whether a given element is in the DOM or not.

Here's a quick example of a component that keeps track of whether it's mounted or not:

class Test extends React.Component {
  render() {
    return (<p>hello</p>);
  }

  componentDidMount () {
    this.mounted = true
    console.log(`mounted: ${this.mounted}`)
  }

  componentWillUnmount () {
    this.mounted = false
    console.log(`mounted: ${this.mounted}`)
  }
}

      



Live example: https://codepen.io/jenius/pen/MmjPJV


Based on this, you should be able to add a simple if / else inside your promise handler to solve your problem!

0


source







All Articles