Multiple redux-sagas Multiple redux-sagas reactjs reactjs

Multiple redux-sagas


Redux Saga uses the all function in the recent version (0.15.3) to combine multiple sagas to one root saga for the Redux store.

import { takeEvery, all } from 'redux-saga/effects';...function *watchAll() {  yield all([    takeEvery("FRIEND_FETCH_REQUESTED", fetchFriends),    takeEvery("CREATE_USER_REQUESTED", createUser)  ]);}export default watchAll;

In the Redux store you can use the root saga for the saga middleware:

import { createStore, applyMiddleware } from 'redux';import createSagaMiddleware from 'redux-saga';import rootReducer from './reducers';import rootSaga from './sagas';const sagaMiddleware = createSagaMiddleware();const store = createStore(  rootReducer,  applyMiddleware(sagaMiddleware));sagaMiddleware.run(rootSaga)


Of course, that is the whole point of sagas.

A typical application will have multiple sagas waiting in the background, waiting for a particular action / actions (take effect).

Below is an example of how you can setup multiple sagas from redux-saga issue#276:

./saga.js

function* rootSaga () {    yield [        fork(saga1), // saga1 can also yield [ fork(actionOne), fork(actionTwo) ]        fork(saga2),    ];}

./main.js

import { createStore, applyMiddleware } from 'redux'import createSagaMiddleware from 'redux-saga'import rootReducer from './reducers'import rootSaga from './sagas'const sagaMiddleware = createSagaMiddleware()const store = createStore(  rootReducer,  applyMiddleware(sagaMiddleware))sagaMiddleware.run(rootSaga)


This has changed a bit since last answers were posted. The preferred way to create root saga, as documented at https://redux-saga.js.org/docs/advanced/RootSaga.html, is using spawn:

export default function* rootSaga() {  yield spawn(saga1)  yield spawn(saga2)  yield spawn(saga3)}

spawn is an effect that will disconnect your child saga from its parent, allowing it to fail without crashing its parent. This simply means that even if one saga were to fail, the rootSaga and other sagas will not be killed.There is also way of recovering sagas that fail (more info on that is available in the link mentioned above).