Blog>
Snippets

Handling API Errors in Sagas

Illustrate how to handle API errors within a saga using 'try catch' blocks and dispatch an error action to the store.
import { call, put } from 'redux-saga/effects';
function* fetchUserData(action) {
  try {
    const data = yield call(Api.fetchUser, action.userId);
    // Dispatch action for successful API call
    yield put({type: 'FETCH_USER_SUCCESS', data});
  } catch (error) {
    // Dispatch action to store on error
    yield put({type: 'FETCH_USER_FAILURE', error});
  }
}
This snippet defines a saga to fetch user data. It uses a 'try catch' block to handle API call errors. On success, it dispatches 'FETCH_USER_SUCCESS' with the data. On failure, it dispatches 'FETCH_USER_FAILURE' with the error.
export function* watchFetchUserData() {
  // Watches for the FETCH_USER_REQUEST action and calls fetchUserData
  yield takeLatest('FETCH_USER_REQUEST', fetchUserData);
}
This snippet sets up a watcher saga that listens for 'FETCH_USER_REQUEST' actions and, when one is received, it triggers 'fetchUserData' saga to handle the actual API request.