Blog>
Snippets

Task Cancellation with `cancel` Effect

Provide an example of cancelling an ongoing saga task using the `cancel` effect, useful in scenarios like aborting a data fetch operation based on specific conditions.
import { take, fork, cancel, call } from 'redux-saga/effects';
function* backgroundTask() {
  // Your background task code here
}

function* watchStartBackgroundTask() {
  while (true) {
    yield take('START_TASK');
    // Fork a new task
    const task = yield fork(backgroundTask);
    // Wait for the cancel action
    yield take('CANCEL_TASK');
    // Cancel the task
    yield cancel(task);
  }
}
This code sets up a saga watcher that listens for a 'START_TASK' action to fork (start) a backgroundTask. When a 'CANCEL_TASK' action is received, it cancels the ongoing backgroundTask using the cancel effect.
import { cancelled } from 'redux-saga/effects';

function* cancellableTask() {
  try {
    // Perform the task
  } catch (error) {
    // Handle errors if any
  } finally {
    if (yield cancelled()) {
      // Logic to run on task cancellation
    }
  }
}
This example shows a cancellableTask saga. It uses the cancelled helper function in the finally block to check if the saga was cancelled and performs cleanup or any other necessary actions upon cancellation.