concept root saga in category react

appears as: root saga
Redux in Action

This is an excerpt from Manning's book Redux in Action.

It may be helpful to think of sagas as subprograms, and the run function on the last line of the listing is required for the subprogram to begin watching for actions. Once the saga middleware is configured, you can run the top-level, or root, saga. In the next section, you’ll get a chance to put a generator into production by writing a root saga.

Listing 6.17. src/sagas.js
import { channel, delay } from 'redux-saga'; #1 import { call, put, take, takeLatest } from 'redux-saga/effects'; #2 ... export default function* rootSaga() { yield takeLatest('FETCH_TASKS_STARTED', fetchTasks); yield takeLatestById('TIMER_STARTED', handleProgressTimer); #3 } function* takeLatestById(actionType, saga) { const channelsMap = {}; #4 while (true) { const action = yield take(actionType); const { taskId } = action.payload; if (!channelsMap[taskId]) { channelsMap[taskId] = channel(); #5 yield takeLatest(channelsMap[taskId], saga); #6 } yield put(channelsMap[taskId], action); #7 } } ... #1 Adds channel to the list of imports #2 Adds take back to the list of effect helper imports #3 Have the root saga initiate the helper function. #4 Stores a mapping of created channels #5 If a task doesn’t have a channel, create one. #6 Creates a new process for that task #7 Dispatches an action to the specific process !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":71},{\"line\":0,\"ch\":73}],[{\"line\":26,\"ch\":0},{\"line\":26,\"ch\":2}],[{\"line\":1,\"ch\":71},{\"line\":1,\"ch\":73}],[{\"line\":27,\"ch\":0},{\"line\":27,\"ch\":2}],[{\"line\":6,\"ch\":71},{\"line\":6,\"ch\":73}],[{\"line\":28,\"ch\":0},{\"line\":28,\"ch\":2}],[{\"line\":10,\"ch\":71},{\"line\":10,\"ch\":73}],[{\"line\":29,\"ch\":0},{\"line\":29,\"ch\":2}],[{\"line\":17,\"ch\":71},{\"line\":17,\"ch\":73}],[{\"line\":30,\"ch\":0},{\"line\":30,\"ch\":2}],[{\"line\":18,\"ch\":71},{\"line\":18,\"ch\":73}],[{\"line\":31,\"ch\":0},{\"line\":31,\"ch\":2}],[{\"line\":21,\"ch\":71},{\"line\":21,\"ch\":73}],[{\"line\":32,\"ch\":0},{\"line\":32,\"ch\":2}]]"} !@%STYLE%@!

6.5.2. Introducing the root saga

The code in the previous listing won’t do anything for you until you write the root saga you imported. Let’s go only far enough to tell that we’ve configured redux-saga properly. Create a new file within the src directory and name it sagas.js. Within that file, write a rootSaga generator function and have it log a message to the console, as shown in the following listing.