2

I want to cancel some functions after component unmount because it causes memory leak my code looks like this

componentDidUpdate(prevProps) {
    if (prevProps.org.org !== this.props.org.org && this.mounted) {
      this.props.clearGraph();
      this.props.graphGet(this.props.org.org);
      this.setState({ org: this.props.org.org });
    }
  }
  componentDidMount() {
      const abox = "a" + this.props.org.org.substr("1");
      this.props.getHistory(abox);
      this.props.graphGet(this.props.org.org);
  }
  componentWillUnmount() {
  }

all I want is to cancel graphGet which is a redux action

Zouari Moez
  • 63
  • 1
  • 9
  • Why you need componentDidUpdate? Did you have store for state? better you pull the state from the father and send it to the child component. In redux you can use mapStateToProps to update a new state. maybe is that the memory leak problem (componentDidUpdate) – Omer Sep 02 '19 at 22:45
  • I didn't understand u could u explain plz – Zouari Moez Sep 02 '19 at 22:47
  • it's not the problem I need to stop graphGet from fetching because I focre update in some cases in other component – Zouari Moez Sep 02 '19 at 22:50
  • Maybe `this.mounted = false;` in componentWillUnmount see this link (https://stackoverflow.com/questions/49906437/how-to-cancel-a-fetch-on-componentwillunmount) – Omer Sep 02 '19 at 22:56
  • if you want to cancel, consider using [`redux saga`](https://redux-saga.js.org/docs/api/) – Joseph D. Sep 03 '19 at 01:43

1 Answers1

2

You cannot cancel Redux actions by design. Once they get dispatched, they are processed by reducers and the state transition is performed.

You can however dispatch another action to revert the state changes or causing side effects. Normally you would use another library like redux-observable for the latter.

You can for example define 3 actions: START_GRAPH_GET, CANCEL_GRAPH_GET and FINISH_GRAPH_GET. On START you start your fetch, on CANCEL you cancel any outstanding fetches and once a fetch completes you dispatch FINISH and keep the result in the store.

In order to render the results you would need to use react-redux connect with a mapStateToProps function.

To cancel on unmount, you would just dispatch an CANCEL action, if necessary.

Since your code does not show anything related to Redux at all, I think a more general answer is reasonable here.

Nappy
  • 3,016
  • 27
  • 39