Implementing Saga Error Handling Patterns
Provide an example of a Redux Saga pattern to handle errors globally within sagas using 'try/catch' blocks and the 'put' effect to dispatch error actions.
import { put, takeLatest } from 'redux-saga/effects';
function* fetchUserData(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: 'FETCH_USER_SUCCESS', user});
} catch (error) {
// Dispatch an error action with the error message
yield put({type: 'FETCH_USER_FAILURE', message: error.message});
}
}
function* watchFetchUserData() {
// Take every action of type 'FETCH_USER_REQUEST' and execute fetchUserData
yield takeLatest('FETCH_USER_REQUEST', fetchUserData);
}
export default watchFetchUserData;
This code registers a Saga watcher that listens for 'FETCH_USER_REQUEST' actions. When such an action is dispatched, it attempts to fetch user data using a fictional Api.fetchUser method. If the fetch is successful, it dispatches a 'FETCH_USER_SUCCESS' action with the fetched user data. If the fetch fails, it catches the error and dispatches a 'FETCH_USER_FAILURE' action with the error message.
import { all } from 'redux-saga/effects';
import watchFetchUserData from './watchFetchUserData';
export default function* rootSaga() {
yield all([
watchFetchUserData(),
// Include other sagas here
]);
}
This is the rootSaga, which combines all individual Saga watchers into a single entry point. In this example, it only includes the watchFetchUserData Saga, but other Sagas can be added to the array passed to the 'all' effect. The rootSaga is typically run with the sagaMiddleware in the store configuration.