Blog>
Snippets

Using `call` Effect for API Calls

Demonstrate using the `call` effect to perform an API request and process the response within a saga.
import { call, put, takeEvery } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from './actions';
import api from './api';
Imports necessary functions and modules. `call`, `put`, and `takeEvery` are imported from redux-saga/effects for handling effects, and action creators for handling actions upon fetching data success or failure. The 'api' module represents an abstracted API call.
function* fetchResource() {
  try {
    const data = yield call(api.getData);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    yield put(fetchDataFailure(error.message));
  }
}
Defines a generator function for fetching data. The `call` effect is used to make an API call in a way that feels synchronous, awaiting the promise returned by `api.getData()`. If the call succeeds, the `fetchDataSuccess` action is dispatched with the data. On failure, `fetchDataFailure` is dispatched with an error message.
function* watchFetchResource() {
  yield takeEvery('FETCH_RESOURCE_REQUEST', fetchResource);
}
Defines a watcher saga that listens for 'FETCH_RESOURCE_REQUEST' actions and triggers `fetchResource` saga in response to this action.
export default function* rootSaga() {
  yield all([watchFetchResource()]);
}
Exports the root saga which combines all watcher sagas using `all` effect. In this case, it includes only one watcher saga, `watchFetchResource`, to keep things simple.