Blog>
Snippets

Setting Up a Watcher Saga to Respond to Actions

Illustrate setting up a watcher saga that listens for specific actions using 'takeEvery' effect and triggers worker sagas in response.
import { takeEvery, call, put } from 'redux-saga/effects';

// Worker saga: Perform the action task
function* handleAction(action) {
  // logic to handle the action, e.g., API call
  try {
    const data = yield call(Api.fetchData, action.payload);
    yield put({ type: 'ACTION_SUCCESS', data });
  } catch (error) {
    yield put({ type: 'ACTION_FAILURE', error });
  }
}
This piece of code defines a worker saga named 'handleAction'. This saga takes an action as an argument and attempts to perform the action's task. Here, an API call is simulated with 'Api.fetchData', passing the action's payload. Upon success, an 'ACTION_SUCCESS' action is dispatched with the fetched data. In case of failure, an 'ACTION_FAILURE' action is dispatched with the error.
import { takeEvery } from 'redux-saga/effects';
import { handleAction } from './pathToYourSagas';

// Watcher saga: Watches for 'ACTION_REQUESTED' actions and triggers handleAction()
function* watchAction() {
  yield takeEvery('ACTION_REQUESTED', handleAction);
}
This code snippet demonstrates setting up a watcher saga named 'watchAction'. This saga uses 'takeEvery' to listen for 'ACTION_REQUESTED' actions. When such an action is dispatched, 'takeEvery' triggers the 'handleAction' worker saga for each 'ACTION_REQUESTED' action, ensuring that all requests are handled concurrently.