How to execute multiple generators based on actions dispatched asynchronously

99封情书 提交于 2021-01-29 08:42:28

问题


I am trying to dispatch multiple actions which will trigger multiple generator functions.

OnClick

dispatch({ type: "ACTION_1", data1});
dispatch({ type: "ACTION_2", data2});

saga.js

function* method1(action){

//...

const response = yield call(api, requestParams);

//...

}

function* method2(action){

//...

const response1 = yield call(api, requestParams1);

//...

//dependent on response1
const response2 = yield call(api, requestParams2);

//...

//dependent on response2
const response3 = yield call(api, requestParams3);

//...
}


function* actionWatcher() {
    yield all([
        takeLatest("ACTION_1", method1),
        takeLatest("ACTION_2", method2),
    ]);
}
export default function* sagas() {
    yield all([actionWatcher()]);
}

OnClick, method1 is called and I can see a network call and there is this error on console Error: Generator is already running.

I have tried takeEvery as well in actionWatcher() method, same error.

How do I achieve this?


回答1:


As per requirement we can create sagas like here method1Saga and method2Saga is required so, i am giving you one example how saga works

//worker : work for our saga 
function* method1(action) {
    // api call : if we have many dependent api calls then we can simply add
    //one more response2 below response1 and we can use response1 in response2 as well because yield wait until we get our response from server 

    const response1 = yield call(api, requestParams); // api call which return type and payload 

    const response2 = ...... 

    yield put(pass_final_response_here); // pass_final_response_here like ( { type : '' , payload : 'your_response' } )
}

//watcher : watch for request 
function* method1Saga() {
yield takeLatest("ACTION_1",method1)
}

// you can create your method2Saga as per above example

function* actionWatcher() {
    yield all([
        method1Saga(),
       //pass your all saga here  
      ]);
}

Finally import actionWatcher.where we are configuring our store and then just run our saga. like

/**
 *  Store Configuration 
 */

 import  { createStore , applyMiddleware } from 'redux';

 import rootReducer from 'your_root_reducer_path';

 //middleware
 import reduxSaga from 'redux-saga';

 //actionWatcherPath
 import actionWatcherPath from 'actionWatcherPath'; // 

 const sagaMiddleware = reduxSaga();

 //store
 const store = createStore(rootReducer,applyMiddleware(sagaMiddleware));

 //run : our actionWatcherPath
 sagaMiddleware.run(actionWatcherPath);

 export default store;


来源:https://stackoverflow.com/questions/59840855/how-to-execute-multiple-generators-based-on-actions-dispatched-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!