Search code examples
reactjsreact-reduxredux-sagareact-boilerplate

How to add multiple sagas to a single container (both saga listen to different actions)


So, I'm new to react-boilerplate and there seems no way to include another saga without effecting the previous saga's functionality (i.e. it doesn't work).

I've tried declaring the sagas as a constant and then passing it in the compose function at the end of the container, but it gives an error that the object is not a function, upon checking utils/injectsaga.js , it is not a function. SO that didn't work for me. I've tried to directly inject the sagas as below.

Injecting multiple reducers works fine, I think on adding the new saga the previous saga gets overwritten? Please suggest me a better way to fix this.

import sreducer from './reducer';

import ereducer from '../FooCreate/reducer'

import ssaga from './saga';

import esaga from '../FooCreate/saga'


useInjectReducer({ key: 'foo', reducer:sreducer });

useInjectReducer({ key: 'foo', reducer:ereducer });

useInjectSaga({ key: 'foo', saga:ssaga });

useInjectSaga({ key: 'foo', saga:esaga });

Solution

  • I believe you'll need to create a single saga similar to a rootSaga[1] that handles starting the sub-sagas. Something like:

    function* componentSaga() {
      // start the two sagas right away - use a different pattern here depending on
      // how your sagas are structured
      yield all([
        ssaga(),
        esaga(),
      ]);
    }
    
    useInjectSaga({key: 'foo', saga: componentSaga});
    

    if your sagas need to be kicked off right away or

    function* componentSaga() {
      yield takeEvery(FOO_ACTION, ssaga);
      yield takeEvery(BAR_ACTION, esaga);
    }
    
    useInjectSaga({key: 'foo', saga: componentSaga});
    

    if you want them to be triggered by actions.

    [1] https://redux-saga.js.org/docs/advanced/RootSaga.html