Blog>
Snippets

Basic Debouncing Implementation with Redux-Saga

Demonstrate how to implement a basic debounce logic in Redux-Saga for an input field to optimize search queries.
import { debounce, takeLatest, put, call } from 'redux-saga/effects';
Imports the necessary Redux-Saga effects for the debounce functionality.
import {searchAPI} from './api'; // Assuming an API function exists for querying
Imports a fictional search API function for demonstration purposes.
function* handleSearch(action) { 
  try { 
    const results = yield call(searchAPI, action.payload); 
    yield put({ type: 'SEARCH_SUCCESS', results }); 
  } catch (error) { 
    yield put({ type: 'SEARCH_FAILURE', error }); 
  } 
}
Defines a worker saga that performs the search operation using the searchAPI and handles success or failure.
function* watchSearch() { 
  yield debounce(500, 'SEARCH_REQUESTED', handleSearch); 
}
Sets up a watcher saga using the debounce effect. This waits for 500ms of inactivity on `SEARCH_REQUESTED` actions before calling the handleSearch saga.
export default function* rootSaga() { 
  yield takeLatest('WATCH_SEARCH', watchSearch); 
}
Root saga that starts the watchSearch saga. This setup allows adding more watchers easily.