Search code examples
reactjsreact-reduxredux-saga

How to run dispatch on a saga function when a button is clicked?


I have a use case where I might be dispatching actions(saga) later in the game. I have an application where user fills out a form and later on when user clicks on submit that time the saga action will be called through which i will get response from api. But i also have another worker saga that run in the initialization time of application. Somehow only initialize works other forks don't work -

sagas/applicationSaga.js

export function* initialize() {
  yield call(getAppInfo);
}

export function* getAppInfo() {
  try {
    const appInfo = (yield call(
      AppApi.getAppInfo
    )).data;
  } catch (e) {
    throw new Error(e);
  }
}

export function* submitDecision({payload}) {
  try {
    const submitDecision = yield call(AppApi.submitDecision, payload)
  } catch (e) {
    throw new Error(e);
  }
}

export function* applicationSaga() {
  yield fork(takeEvery, ActionTypes.INITIALIZATION_REQUESTED, initialize);
  yield fork(takeEvery, ActionTypes.SUBMIT_DECISION, submitDecision)
}

sagas/index.js

import { applicationSaga, initialize } from "./applicationSaga";

export default function* rootSaga() {
  yield all([applicationSaga(), initialize()]);
}

Solution

  • I got the way to implement this -

    export function* initialize() {
      yield take(ActionTypes.INITIALIZATION_REQUESTED);
      yield call(getAppInfo);
    }
    
    export function* submitDecision({payload}) {
      try {
        const submitDecision = yield call(AppApi.submitDecision, payload)
      } catch (e) {
        throw new Error(e);
      }
    }
    export function* applicationSaga() {
      yield all([
        initialize(),
        takeEvery(ActionTypes.SUBMIT_DECISION, submitDecision)
      ]);
    }
    

    sagas/index.js

    import { all } from "redux-saga/effects";
    import { applicationSaga } from "./applicationSaga";
    
    export default function* rootSaga() {
      yield all([applicationSaga()]);
    }
    

    Basically I had to yield all in root saga and in my actual application saga I can keep adding workers attaching to my watcher saga.