Blog>
Snippets

Implementing a TakeEvery Saga

Demonstrate how to use the TakeEvery effect to listen for dispatched actions and execute a function to handle asynchronous API calls.
import { takeEvery, call, put } from 'redux-saga/effects';
import { FETCH_DATA, fetchDataSuccess, fetchDataFailure } from './actions';
import { fetchDataFromApi } from './api';
Imports necessary functions and action creators, including the action type we're listening for ('FETCH_DATA'), and the actual API call function ('fetchDataFromApi').
function* fetchDataSaga(action) {
  try {
    const data = yield call(fetchDataFromApi, action.payload);
    yield put(fetchDataSuccess(data));
  } catch (error) {
    yield put(fetchDataFailure(error.message));
  }
}
Defines a saga to handle API calls. When 'FETCH_DATA' action is dispatched, this saga is triggered. It then attempts to fetch data using 'fetchDataFromApi', and dispatches either a success or failure action based on the call result.
function* watchFetchData() {
  yield takeEvery(FETCH_DATA, fetchDataSaga);
}
Creates a watcher saga that listens for the 'FETCH_DATA' action. Each time the action is dispatched, the 'fetchDataSaga' is executed.
export default watchFetchData;
Exports the watcher saga as default, making it available for integration with the middleware setup in the store configuration.