Search code examples
redux-saga

How to cancel the task in Saga if takeLatest is used?


I have many forms in the app and to reuse the same form, but with different 'id' I have created a component, with this saga:

export default function FormSaga(SEND_REQUEST) {
  return function* () {
    yield takeLatest(SEND_REQUEST, submit);
  };
}

But if I need to abort the form submission, Saga's manual is offering me this solution:

function* main() {
  while ( yield take('START_BACKGROUND_SYNC') ) {
    // starts the task in the background
    const bgSyncTask = yield fork(bgSync)

    // wait for the user stop action
    yield take('STOP_BACKGROUND_SYNC')
    // user clicked stop. cancel the background task
    // this will cause the forked bgSync task to jump into its finally block
    yield cancel(bgSyncTask)
  }
}

I tried this:

export default function FormSaga(SEND_REQUEST, ABORT_REQUEST) {
  return function* () {
    while (yield take(SEND_REQUEST)) {
      const submitTask = yield fork(submit);

      yield take(ABORT_REQUEST);
      yield cancel(submitTask);
    }
  };
}

But it is not working.

If somebody could help me rewrite my takeLatest so the task cancellation would work? Thank you!


Solution

  • Guess found the solution, looks like it is working.

        const task = yield takeLatest(SEND_REQUEST, submit);
    
        yield take(ABORT_REQUEST);
        yield cancel(task);