Blog>
Snippets

Error Handling in Batched Actions

Illustrate proper error handling techniques for batched actions in Redux-Saga, ensuring that failures in one part of the batch do not halt the entire process.
import { all, call, put } from 'redux-saga/effects';

function* batchedActionsWorker(action) {
  try {
    const responses = yield all([
      call(apiCallOne, action.payload),
      call(apiCallTwo, action.payload)
    ]);
    // Dispatch success actions for each call
    yield put({type: 'ACTION_ONE_SUCCESS', payload: responses[0]});
    yield put({type: 'ACTION_TWO_SUCCESS', payload: responses[1]});
  } catch (error) {
    // Dispatch failure action, noting the batched action failed
    yield put({type: 'BATCHED_ACTIONS_FAILURE', error});
  }
}
This snippet demonstrates error handling with Redux-Saga for batched actions. It attempts to concurrently execute two API calls using 'all'. If any of the calls fail, an error is caught in the catch block, and a failure action is dispatched to handle the error. This prevents the failure of one part from halting the entire batch, allowing individual success actions to be dispatched for each successful call.
import { put } from 'redux-saga/effects';

function* safePut(action) {
  try {
    yield put(action);
  } catch (error) {
    console.error('Failed to dispatch action', action.type, error);
    // Optionally, dispatch an error action or handle it as needed
  }
}

function* batchedActionsWithSafePut() {
  yield all([
    call(safePut, { type: 'ACTION_ONE', payload: { /* Some payload */ } }),
    call(safePut, { type: 'ACTION_TWO', payload: { /* Some payload */ } })
  ]);
}
Here, a 'safePut' wrapper function is utilized to handle errors for each action within the batch individually. This method allows each 'put' operation within a batch to be executed securely, catching and logging errors for each action without affecting others in the batch. This pattern could be beneficial for cases where it's crucial to attempt all actions in a batch, handling their success or failure independently.