Implementing a Debounce in Sagas
Show how to use `debounce` effect in Redux-Saga to delay the API call actions until after a specified wait time, effectively reducing the number of calls made during rapid firing events like typing in a search bar.
import { debounce, put, call } from 'redux-saga/effects';
Import necessary effects from redux-saga, including 'debounce' for debouncing actions.
function* handleSearch(action) {
// Perform the API call
const data = yield call(fetchDataFromAPI, action.payload);
// Dispatch action with the result from the API
yield put({ type: 'SEARCH_SUCCESS', data });
}
Defines a saga to handle the search functionality, making an API call with the action payload and dispatching a success action with the API data.
function* watchSearch() {
// Use debounce effect to delay the search action handling
// Waits for 500ms before executing handleSearch
yield debounce(500, 'SEARCH_REQUESTED', handleSearch);
}
Watcher saga uses the 'debounce' effect to wait for 500ms of inactivity on 'SEARCH_REQUESTED' actions before invoking the handleSearch saga. This reduces the number of API calls during rapid typing events.