Blog>
Snippets

Utilizing the takeEvery Effect with Middleware

Showcase the use of takeEvery effect in a saga to intercept specific actions and leverage middleware to log the action details and the results of the saga execution.
import { takeEvery, call, put } from 'redux-saga/effects';
import { LOG_ACTION, FETCH_SUCCESS, FETCH_FAILED } from './actionTypes';
import Api from './path/to/api';
Imports necessary effects from redux-saga and action types from actionTypes file, along with the API wrapper.
function* logAction(action) {
  console.log('Action intercepted by saga:', action);
}
Defines a generator function for logging actions intercepted by the saga.
function* fetchUserData(action) {
  try {
    const data = yield call(Api.fetchUser, action.payload);
    yield put({ type: FETCH_SUCCESS, data });
  } catch (error) {
    yield put({ type: FETCH_FAILED, message: error.message });
  }
}
Defines a generator function to fetch user data using the API and handles success and failure scenarios.
function* mySaga() {
  yield takeEvery(LOG_ACTION, logAction);
  yield takeEvery('FETCH_USER_REQUEST', fetchUserData);
}
Root saga combines both intercepting log actions and fetching user data on each corresponding action dispatched.