Debouncing a search input
Illustrate debouncing user input in Redux-Saga to limit API calls while searching, utilizing the debounce effect.
import { debounce, put, call } from 'redux-saga/effects';
import { SEARCH_REQUESTED, searchSuccess, searchFailure } from './actions';
import { fetchSearchResults } from './api';
First, import necessary effects from redux-saga and actions from your actions file. Also, import the API call function.
function* handleSearch(action) {
try {
const results = yield call(fetchSearchResults, action.payload);
yield put(searchSuccess(results));
} catch (error) {
yield put(searchFailure(error.message));
}
}
Define the saga that handles the search. It uses the call effect to invoke the API and put to dispatch success or failure actions.
function* watchSearch() {
yield debounce(500, SEARCH_REQUESTED, handleSearch);
}
This watcher saga uses the debounce effect to delay the search action until 500ms have passed without any other SEARCH_REQUESTED actions being dispatched. This reduces the number of API calls when the user types quickly.
export default watchSearch;
Export the watcher saga so it can be used in the saga middleware.