In Redux-Saga, you can terminate an active task by using the cancel effect or by reacting to a specific action, such as LOGOUT. This functionality is beneficial for halting ongoing background processes, including API polling, fetch requests, or watchers.
1. Manual Cancellation with cancel()
import { call, cancel, fork, take } from 'redux-saga/effects';
function* backgroundTask() {
// some long-running or blocking task
yield call(apiCall);
}
function* mainSaga() {
const task = yield fork(backgroundTask); // run task in the background
yield take('CANCEL_TASK'); // wait for cancel action
yield cancel(task); // cancel the running task
}
2. Auto Cancellation Using takeLatest
takeLatest automatically cancels any previous task if a new one comes in:
import { takeLatest, call } from 'redux-saga/effects';
function* fetchData(action) {
yield call(apiCall, action.payload);
}
function* watchFetch() {
yield takeLatest('FETCH_REQUEST', fetchData);
}