Blog>
Snippets

Automatically Cancelling Tasks with takeLatest

Provide an example of using `takeLatest` effect to automatically cancel previous tasks if a new action is dispatched, useful for search input that triggers an API call.
import { takeLatest, call, put } from 'redux-saga/effects';
Importing necessary effects from redux-saga.
import { searchAPI } from './pathToAPI'; // Path to your API call
Importing API call function for searching.
function* handleSearch(action) {
  try {
    const results = yield call(searchAPI, action.payload);
    yield put({ type: 'SEARCH_SUCCESS', results });
  } catch (e) {
    yield put({ type: 'SEARCH_FAILED', message: e.message });
  }
}
Defining a saga to handle the search API call which uses 'call' to call the API and 'put' to dispatch actions based on the API call result.
export function* watchSearch() {
  yield takeLatest('SEARCH_REQUEST', handleSearch);
}
Utilizing takeLatest to automatically cancel any previous saga task started on every 'SEARCH_REQUEST' action if a new 'SEARCH_REQUEST' action is dispatched.