Blog>
Snippets

Employing the Call Effect for API Requests

Example of using the Call effect to make an API request within a saga, demonstrating how generator functions can be used to handle asynchronous operations.
import { call, put } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailed } from './actions';
import { fetchDataApi } from './api';
Import necessary effects from redux-saga and action creators from the actions file, as well as the API fetch function.
function* fetchDataSaga(action) {
  try {
    const data = yield call(fetchDataApi, action.payload);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    yield put(fetchDataFailed(error.message));
  }
}
Define a generator function, fetchDataSaga, that attempts to fetch data using the fetchDataApi function. Upon success, it dispatches a success action with the data. On failure, it dispatches a failed action with the error message.
export default fetchDataSaga;
Exports the fetchDataSaga generator function for use in the saga middleware.