How do I use yield inside a callback on redux-saga?

Viewed 1235

I have a callback which I need to return true or false to trigger some external action, I need to make an API call inside this callback, so I need to get the state and dispatch some actions inside the callback, I don't know if I can use eventChannel because this callback could not be a generator, only a plain function. I need to do something like this.

  zafClient.on('ticket.save', () => {
      const state = yield select();
      yield put(actionWithApiCall())

      // I need to wait for the action to finish and then return something 
      // based on the response from the API
      // I know how to block the saga to wait for the action dispatched 
      // the problem is that I can't use yield here

      return somethingfromthestore;
  });

Btw, this is zendesk API.

2 Answers

Your not going to be able to pass a generator function to that API. The work around is to dispatch an action directly to the redux store and then write a saga that listens for that action.

zafClient.on('ticket.save', () => reduxStore.dispatch(actionWithApiCall()))

You will have to make the redux store exportable from where you create it. So that you can directly access it here.

One of the challenges is how to yield in the callback. How about importing dispatch? Isn't dispatch the non-generator version of yield?

Should you be using React, doing so seems to be an option.

In the same saga that you use to specify the callback, you can subsequently listen for the action created in the dispatch/action creator callback. That's done by specifying another watchFor function (in my setup, any number of exported watchFor functions get added to the pool of saga watchers).

The paired saga worker can finalize whatever needs to happen to the data returned from the API call before using your final action creator to "document" the workflow by updating the store.

The other option might be to wrap the api call in an eventChannel (see: https://github.com/redux-saga/redux-saga/issues/1178).

- E

Related