Blog>
Snippets

Using Debounce in Sagas for Search Input

Show how to implement debouncing in a saga to optimize API calls triggered by user input in a search field, using the 'debounce' effect to delay the API call until the user stops typing.
import { debounce, put, call } from 'redux-saga/effects';
import { fetchResults } from './api';
import { setResults, searchInitiated } from './actions';
Imports required functions and variables from redux-saga, the API call function, and the actions to dispatch.
function* fetchSearchResults(action) {
  try {
    const data = yield call(fetchResults, action.payload);
    yield put(setResults(data));
  } catch (error) {
    console.error('Search API call failed', error);
    // Handle the error appropriately
  }
}
Saga worker function that gets called by the debounced watcher saga. It performs the API call and dispatches the result.
function* watchSearchInput() {
  yield debounce(500, searchInitiated.toString(), fetchSearchResults);
}
Watcher saga that introduces debouncing. It waits for 500ms after the last dispatched searchInitiated action before calling the worker saga.