Blog>
Snippets

Cancelling a Detached Task

Provide an example of explicitly cancelling a detached task created with `spawn`, using the `cancel` effect, to showcase the need for manual intervention.
import { spawn, cancel } from 'redux-saga/effects';

function* sagaWorker() {
  // Task to be performed by the worker
}

function* sagaWatcher() {
  // Spawning a detached task
  const task = yield spawn(sagaWorker);
  
  // Cancel the detached task explicitly
  yield cancel(task);
}
This code snippet demonstrates how to explicitly cancel a detached task created using `spawn`. `sagaWorker` is the task that is being run as a detached task by using `spawn` in `sagaWatcher`. The task is then cancelled explicitly using the `cancel` effect.