Wahtel
Wahtel

Reputation: 161

How to pass function to the callback inside redux-saga using eventChannel

I have redux-saga which makes a lot of stuff with the current session etc. Inside of one of my generator functions inside this saga I have a place which looks like this:

setSessionFailureHandler(() => {
  yield openMFAModal(account);
});

setSessionFailureHandler is the 3-rd party SDK inside which I need to pass a callback. openMFAModal is the redux action which opening the modal window. I'm using callback function from 3-d party SDK which should handle session failure and open modal window. Of course, I can't use yield inside the callback, that's why I'm trying to use eventChannel feature, I created a new function for the channel it looks like this:

function setSessionFailureChannel(data) {
  return eventChannel((emitter) => {
    setSessionFailureHandler(() => {
      const { function, account } = data;
      return emitter(function(account));
    });
  });
}

Inside another generator, I'm trying to call this function with the callback but honestly for me not clear how to do this, all samples what I saw regarding eventChannel focused on the idea to pass some data through callBack to your saga, but what I need is to pass somehow my action to the callback which will call it after handle session failure.

I'm trying to pass my action and argument for this action from my generator to this function like this:

const setSessionFailure = yield call(setSessionFailureChannel, { func: openMFAModal, account });
while (true) {
   yield call(setSessionFailure);
}

I know that it's the wrong approach, maybe someone did the same trick somehow and can explain how to do this correct?

Upvotes: 1

Views: 1078

Answers (1)

azundo
azundo

Reputation: 6052

You need to yield take from the channel, so something like:

const setSessionFailureChan = yield call(setSessionFailureChannel, { func: openMFAModal, account });
while (true) {
   // the channel yields actions due to the way you've structured the emitter
   const openMFAModalAction = yield take(setSessionFailureChan);
   // then you need to dispatch those actions
   yield put(openMFAModalAction);
}

This is assuming you updated the setSessionFailureChannel code to use func instead of function when destructuring data as I imagine you already have.

Upvotes: 1

Related Questions