Blog>
Snippets

Using takeLatest to Prevent Multiple Instances

Demonstrates how to use 'takeLatest' pattern to automatically cancel any previously started tasks of the same type when a new action is dispatched.
import { takeLatest } from 'redux-saga/effects';

function* fetchData(action) {
  // Your data fetching logic here
}

function* watchFetchData() {
  // Automatically cancels any previously fired fetchData tasks
  // and fires a new fetchData task
  yield takeLatest('FETCH_REQUESTED', fetchData);
}
This example shows how to use the 'takeLatest' effect from Redux-Saga to ensure that if the 'FETCH_REQUESTED' action is dispatched multiple times, only the latest invocation will take effect. Previous ongoing 'fetchData' tasks, if any, will be cancelled before starting a new one.