Search code examples
redux-saga

Redux-Saga - cancel all other sagas when cancel action is fired


In my project I have a root saga that watches several actions and makes some API calls. In some cases I want to cancel those sagas and API calls.

Now it is composed like that:

export default function*() {
  yield all([
    takeLatest(ActionTypes.GET_ACTION_ONE, getOneSaga),
    takeLatest(ActionTypes.GET_ACTION_TWO, getTwoSaga),
  ]);
}

And I have ActionTypes.CANCEL, and when it's fired I want any other saga (getOneSaga and getTwoSaga) to be cancelled and I want to manage yield cancelled() to cancel API calls inside them.

So, how do I compose all of my actions and cancel action.


Solution

  • You could use race effect:

    export default function* () {
      yield race([
        take(ActionTypes.CANCEL),
        all([
          takeLatest(ActionTypes.GET_ACTION_ONE, getOneSaga),
          takeLatest(ActionTypes.GET_ACTION_TWO, getTwoSaga),
        ]),
      ]);
    }
    

    Creates an Effect description that instructs the middleware to run a Race between multiple Effects. When resolving a Race, the middleware automatically cancels all the losing Effects