Making an API Call with Redux Saga
Demonstrate how to perform a single API call using the `call` effect in Redux Saga, handling success and failure scenarios.
import { call, put } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from '../actions/dataActions';
import { fetchDataFromAPI } from '../api';
function* fetchDataSaga(action) {
try {
// make the API call
const data = yield call(fetchDataFromAPI);
// dispatch a success action to the store with the new data
yield put(fetchDataSuccess(data));
} catch (error) {
// dispatch a failure action to the store with the error
yield put(fetchDataFailure(error));
}
}
This code defines a Redux Saga generator function called fetchDataSaga. It attempts to make an API call using the call effect, which is used for calling a function (fetchDataFromAPI in this case). If the API call succeeds, the generator yields a put effect to dispatch a success action (fetchDataSuccess) with the fetched data as payload. In the case of an error, it yields a put effect to dispatch a failure action (fetchDataFailure) with the error as payload, handling both success and failure scenarios.