Blog>
Snippets

Fetching data with call effect

Demonstrate how to use the call effect in Redux-Saga for making API calls and handling the received data.
import { call, put } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataError } from './actions';
import api from './api';
Importing necessary effects from redux-saga, action creators, and the API call function.
function* fetchAPIData() {
  try {
    // Making an API call using the call effect
    const data = yield call(api.fetchData);
    // Dispatching a success action with the fetched data
    yield put(fetchDataSuccess(data));
  } catch (error) {
    // Dispatching an error action in case of failure
    yield put(fetchDataError(error.message));
  }
}
A generator function that uses the call effect to make an API request and process the response or error.
export default fetchAPIData;
Exporting the saga to be used in the saga middleware configuration.