Blog>
Snippets

Combining Throttle with takeLatest

Demonstrate the combination of throttle and takeLatest effects in Redux-Saga to manage both throttling and taking only the latest action.
import { throttle, takeLatest, call, put } from 'redux-saga/effects';
import { fetchData } from './api';
import { FETCH_REQUESTED, FETCH_SUCCEEDED, FETCH_FAILED } from './actions';
First, import the necessary functions and constants from redux-saga/effects, your API, and your action types.
function* fetchDataSaga(action) {
  try {
    const data = yield call(fetchData, action.payload.query);
    yield put({ type: FETCH_SUCCEEDED, payload: data });
  } catch (error) {
    yield put({ type: FETCH_FAILED, payload: error });
  }
}
Define the fetchDataSaga generator function. This function tries to fetch data using the fetchData function and dispatches either a success or failure action.
function* watchFetchDataSaga() {
  yield throttle(500, FETCH_REQUESTED, takeLatest, fetchDataSaga);
}
Define the watchFetchDataSaga generator function. It uses throttle combined with takeLatest to control the saga execution. It waits for the latest FETCH_REQUESTED action within a 500ms interval, effectively limiting the frequency at which fetchDataSaga can be called to handle FETCH_REQUESTED actions.