Blog>
Snippets

Managing Asynchronous Flows with Debounce in Redux-Saga

Use `debounce` from Redux-Saga to manage rapid, consecutive actions (such as user input) by waiting for a pause before triggering a saga, effectively reducing unnecessary loads or calls.
import { debounce, put, call } from 'redux-saga/effects';

// Saga watcher
function* watchInput() {
  yield debounce(500, 'INPUT_CHANGED', handleInput);
}
Defines a saga watcher that uses debounce to wait for 500ms of inactivity on 'INPUT_CHANGED' actions before calling handleInput saga.
import { fetchData } from './api';

// Saga worker
function* handleInput(action) {
  try {
    const data = yield call(fetchData, action.payload);
    yield put({ type: 'FETCH_SUCCEEDED', data });
  } catch (error) {
    yield put({ type: 'FETCH_FAILED', error });
  }
}
Defines the handleInput saga that is called after the debounce period. It fetches data and puts a success or fail action based on the result.