Blog>
Snippets

Using takeLatest to Prevent Multiple Requests

Demonstrate how to use the 'takeLatest' effect in a saga to automatically cancel any previously started tasks if a new 'FETCH_USER_REQUEST' action is dispatched.
import { takeLatest, call, put } from 'redux-saga/effects';
import { fetchUserApi } from './api';
import { FETCH_USER_REQUEST, fetchUserSuccess, fetchUserFailure } from './actions';
Imports necessary effects from redux-saga/effects, the API call function, and action creators.
function* fetchUser(action) {
  try {
    const user = yield call(fetchUserApi, action.payload.userId);
    yield put(fetchUserSuccess(user));
  } catch (error) {
    yield put(fetchUserFailure(error.message));
  }
}
The worker saga 'fetchUser' attempts to fetch user data using the provided userId from the action payload, dispatches a success action with the user data on success, or a failure action with an error message on failure.
function* watchFetchUserRequest() {
  yield takeLatest(FETCH_USER_REQUEST, fetchUser);
}
The watcher saga uses takeLatest to listen for 'FETCH_USER_REQUEST' actions. If a request is made while a previous one is still in process, the previous one is cancelled and only the latest request is handled.
export default watchFetchUserRequest;
Exports the watcher saga for inclusion in the root saga.