Blog>
Snippets

Error Handling in Throttled Sagas

Show how to handle errors gracefully in a throttled Redux-Saga scenario, ensuring robust application behavior.
import { take, call, put, throttle } from 'redux-saga/effects';

function* fetchData(action) {
  try {
    // Imagine fetchApi is a function to call your API
    const data = yield call(fetchApi, action.payload);
    yield put({ type: 'FETCH_SUCCESS', data });
  } catch (error) {
    yield put({ type: 'FETCH_FAILED', error });
  }
}
This is a worker saga that attempts to fetch data when it's called. It wraps the API call in a try-catch block to handle errors gracefully. On success, it dispatches a 'FETCH_SUCCESS' action with the data. On failure, it dispatches a 'FETCH_FAILED' action with the error.
import { throttle } from 'redux-saga/effects';
import { fetchData } from './sagas';

function* watchFetchData() {
  // Throttles the fetchData saga to only run once every 2000 milliseconds for actions of type 'FETCH_REQUEST'
  yield throttle(2000, 'FETCH_REQUEST', fetchData);
}
This is a watcher saga that uses the throttle effect from Redux-Saga to limit the execution of the fetchData saga to once every 2000 milliseconds. It listens for 'FETCH_REQUEST' actions and delegates the work to the fetchData saga, ensuring that it's not called more frequently than the throttling limits.