Error Handling in Redux-Saga
Provide a code snippet on how to implement error handling within a Saga function, using try-catch blocks to gracefully handle API call failures.
import { call, put } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from './actionCreators';
import Axios from 'axios';
function* fetchUserData() {
try {
const response = yield call(Axios.get, 'https://example.com/api/user');
// Dispatch success action with the response data
yield put(fetchDataSuccess(response.data));
} catch (error) {
// Dispatch failure action with the error message
yield put(fetchDataFailure(error.message));
}
}
This code snippet demonstrates a Redux-Saga generator function named fetchUserData. It attempts to fetch user data from an API using Axios. If the API call is successful, it dispatches a success action with the data received. If the API call fails, it catches the error and dispatches a failure action with the error message. This approach ensures that the application can handle API failures gracefully.