Blog>
Snippets

Debouncing a Search Input with Redux-Saga

Provide an example of using the 'debounce' effect in Redux-Saga to handle API calls for a search input efficiently, preventing unnecessary requests while typing.
import { debounce, put, call } from 'redux-saga/effects';

function* handleSearch(action) {
  // Call your API with query from action.payload
  const results = yield call(api.search, action.payload.query);
  // Dispatch action with the results to redux store
  yield put({ type: 'SEARCH_SUCCESS', payload: results });
}
This saga listens for 'SEARCH_REQUEST' actions and uses the debounce effect to postpone execution until 500ms have elapsed since the last time this saga was invoked with a 'SEARCH_REQUEST' action. It then calls the API and dispatches the results.
export function* watchSearch() {
  yield debounce(500, 'SEARCH_REQUEST', handleSearch);
}
A watcher saga that employs the debounce effect to watch for 'SEARCH_REQUEST' actions and invokes handleSearch.