Blog>
Snippets

Implementing Saga for Asynchronous Data Fetching

Showcase how to implement a saga that handles asynchronous data fetching from an API, including triggering loading states and handling received data or errors.
import { call, put, takeLatest } from 'redux-saga/effects';
import axios from 'axios';

// Action Types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
Imports necessary dependencies and defines action types for the data fetching lifecycle.
function fetchDataFromAPI() {
  return axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.data)
    .catch(error => { throw error; });
}
Defines a function to fetch data from an API using axios. It handles both successful responses and errors.
function* fetchDataSaga() {
  try {
    // Trigger loading state
    yield put({ type: FETCH_DATA_REQUEST });
    const data = yield call(fetchDataFromAPI);
    // Dispatch success action with fetched data
    yield put({ type: FETCH_DATA_SUCCESS, payload: data });
  } catch (error) {
    // Dispatch failure action if an error occurs
    yield put({ type: FETCH_DATA_FAILURE, error });
  }
}
Defines the main saga to handle the asynchronous data fetching. It uses the call effect to fetch data, and put effect to dispatch actions based on the fetch result.
function* watchFetchDataSaga() {
  // Take the latest action and cancel any ongoing FETCH_DATA_REQUEST actions
  yield takeLatest(FETCH_DATA_REQUEST, fetchDataSaga);
}
Sets up a watcher saga using takeLatest to listen for FETCH_DATA_REQUEST actions and run fetchDataSaga, ensuring that if the action is dispatched multiple times, only the result of the latest request is handled.
export default watchFetchDataSaga;
Exports the watcher saga which can be imported and used in the saga middleware.