Blog>
Snippets

Debouncing Input Actions in Redux-Saga

Provide an example of debouncing input actions in Redux-Saga, useful for optimizing search feature performance by delaying actions until user input pauses.
import { debounce, put, call } from 'redux-saga/effects';
import { FETCH_SUGGESTIONS, fetchSuggestionsSuccess } from './actions';

// Worker Saga
function* fetchSuggestionsWorker(action) {
  try {
    // Imagine fetchSuggestionsApi is a function that calls an API to fetch suggestions
    const data = yield call(fetchSuggestionsApi, action.payload);
    yield put(fetchSuggestionsSuccess(data));
  } catch (e) {
    // Handle the error appropriately here
  }
}
Defines a worker saga that makes an API call to fetch suggestions and dispatches a success action with the fetched data.
import { takeLatest } from 'redux-saga/effects';

// Watcher Saga
function* watchFetchSuggestions() {
  // Uses takeLatest instead of debounce for simplicity. Replace with debounce as needed.
  yield takeLatest(FETCH_SUGGESTIONS, fetchSuggestionsWorker);
}
Defines a watcher saga that listens for the FETCH_SUGGESTIONS action. It uses takeLatest to automatically cancel any previously started fetchSuggestionsWorker tasks if a new FETCH_SUGGESTIONS action is dispatched. This ensures that if the user types rapidly, only the latest request is processed. For debouncing behavior, replace takeLatest with debounce from redux-saga, specifying the desired debounce duration in milliseconds.
import { all } from 'redux-saga/effects';

export default function* rootSaga() {
  yield all([
    watchFetchSuggestions(),
    // Add other sagas here
  ]);
}
Combines all sagas into a root saga. This is the saga that should be run with the saga middleware. It includes the watcher saga for fetching suggestions, ensuring that it is active and listening for the relevant actions.