Blog>
Snippets

Initiating Task Cancellation in Response to an Action

Shows how to use the 'cancel' effect to stop an ongoing saga task when a specific Redux action is dispatched.
import { take, fork, cancel } from 'redux-saga/effects';

function* backgroundTask() {
  // Task logic goes here
  try {
    // Simulate background work
    while(true) {
      console.log('Task is running');
      yield delay(1000); // Wait for 1 second
    }
  } finally {
    console.log('Task is either completed or was cancelled');
  }
}

function* watchStartStopBackgroundTask() {
  while (true) {
    // Wait for the action to start the background task
    yield take('START_BACKGROUND_SYNC');
    // Fork a new task
    const task = yield fork(backgroundTask);
    // Wait for the action to stop/cancel the background task
    yield take('STOP_BACKGROUND_SYNC');
    // Cancel the task
    yield cancel(task);
    console.log('Background task was cancelled');
  }
}
This code snippet demonstrates the process of initiating task cancellation in response to an action in a Redux Saga environment. It makes use of the 'take', 'fork', and 'cancel' effects. The saga waits for a 'START_BACKGROUND_SYNC' action to fork a new background task and then waits for a 'STOP_BACKGROUND_SYNC' action to cancel the ongoing task.