Blog>
Snippets

Handling API Calls with call Effect in Redux Saga

Show how to use the `call` effect to make an API call and handle the response or catch errors in a Redux Saga.
import { call, put, takeEvery } from 'redux-saga/effects';
import axios from 'axios';

// Redux action types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_ERROR = 'FETCH_DATA_ERROR';

// Function to make the API call
function apiFetch(url) {
  return axios.get(url);
}

// Worker saga: makes the API call when watcher saga sees the action
function* fetchSaga(action) {
  try {
    const response = yield call(apiFetch, action.url);
    // Dispatch a success action to the store with the new data
    yield put({ type: FETCH_DATA_SUCCESS, payload: response.data });
  } catch (error) {
    // Dispatch an error action to the store with the error message
    yield put({ type: FETCH_DATA_ERROR, payload: error.message });
  }
}

// Watcher saga: spawns a new fetchSaga on each FETCH_DATA_REQUEST action
function* watchFetchSaga() {
  yield takeEvery(FETCH_DATA_REQUEST, fetchSaga);
}

export default watchFetchSaga;
This code demonstrates how to use Redux-Saga's `call` effect to make API calls. The `apiFetch` function uses axios to get data from a URL. The `fetchSaga` worker saga is triggered by the `FETCH_DATA_REQUEST` action, makes the API call using `call`, and then dispatches either a `FETCH_DATA_SUCCESS` action with the data on success or a `FETCH_DATA_ERROR` action with the error message on failure. The `watchFetchSaga` watcher saga listens for `FETCH_DATA_REQUEST` actions and triggers `fetchSaga`.