Blog>
Snippets

Handling Asynchronous Data Fetching

Demonstrate how to use Redux Saga for asynchronous data fetching with an API call using the 'call' and 'put' effects to handle success and error responses.
import { call, put, takeLatest } from 'redux-saga/effects';
import { fetchDataSuccess, fetchDataFailure } from './actionCreators';
import { FETCH_DATA_REQUEST } from './actionTypes';
import Api from '...'; // Assume this is your API file
This is the import statement where we import necessary effects from redux-saga, our action creators, actionTypes, and the API file.
function* fetchData(action) {
  try {
    const data = yield call(Api.fetchData, action.payload);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    yield put(fetchDataFailure(error.message));
  }
}
This generator function 'fetchData' performs the async API call using 'call' effect, and handles success or failure using 'put' effect to dispatch corresponding actions.
function* watchFetchData() {
  yield takeLatest(FETCH_DATA_REQUEST, fetchData);
}
This watcher saga waits for the FETCH_DATA_REQUEST action and calls fetchData saga. It uses 'takeLatest' to cancel any ongoing fetchData saga and run the latest one.
export default function* rootSaga() {
  yield all([
    watchFetchData(),
    // You can add more watchers here
  ]);
}
The rootSaga combines all the watcher sagas. Using 'all' effect, we can run multiple sagas concurrently.