'How to call generator functions with React-Thunk

I'm in the process of converting some sagas to thunks. Some of these sagas have nested generator functions that I'm not able to call within thunks. Normally in a saga I do:

 const result = yield call(myFunction, anotherSaga, params);

However when i try to convert this to thunk like:

export const myAction = createAsyncThunk(
  'myAction',
  async (data: Payload, { dispatch, getState }) => {

     const result = myFunction(anotherSaga, params).next().value;

     console.log(result)
})

console:
    @@redux-saga/IO: true
    combinator: false
    payload: {context: null, args: Array(2), fn: ƒ}
    type: "CALL"

I don't get anything usable as anotherSaga has nested sagas. How can I convert this to a thunk function?



Solution 1:[1]

You can't directly call saga from a thunk, the effects that sagas use need to be processed by the saga library.

Some possible workarounds:

a) Convert even the nested saga to non-generator function

b) If the result isn't important you can replace the call with a dispatch instead and then use takeEvery effect to call the saga when such an action is dispatched

c) I wouldn't recommend this, but it is technically possible to run the saga using the saga middleware instance

export const myAction = createAsyncThunk(
  'myAction',
  async (data: Payload, { dispatch, getState }) => {
     const task = sagaMiddleware.run(anotherSaga, params)
     const result = await task.toPromise()
     console.log(result)
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Kadlec