2

Having react & redux application that using asynchronous calls via Axios, I need to cancel such request that are still in progress once the user navigate to other page or anything else. Being new to react I came up with an idea to keep the axios cancelToken in redux state and cancel it in componentWillUnmount() of the react component.

example:

componentWillUnmount() {
  const (isLoading, cancelToken} = this.props;
  if (isLoading) {
    cancelToken.cancel("Abort request");
  }
}

Are there better patterns or solution to this?

EDIT: Async call is being fired in redux-thunk i.e. action

Smolda
  • 882
  • 5
  • 13
  • 34

1 Answers1

1

It depends on where you have implemented your fetch.

If you have placed it within your component, you can fire the cancel event in the componentWillUnmount method.

If you have placed it in a middleware such as redux-saga, you can create and use the cancel token then and there itself.

If it is within an action creator you can try the method suggested here

Easwar
  • 5,132
  • 1
  • 11
  • 21