Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to wait for an action in redux-sagas?

I have a saga (A) which fetches the API. This is tied with action (a). I want to trigger an action (b) which internally calls (a), waits for it to finish and then yield something.

// saga A -> action_a
function *saga_a(action) {
  yield put( ...action1...);
  yield call(api, ...params);
  yield put( ...action2...);
}


// saga B -> action_b
function *saga_b(action) {
  yield put(..action3..)

  waitFor -- put(action_a)     <------ how to achieve this?

  yield put(..action4..)
 }
like image 1000
ankit_m Avatar asked Jun 27 '17 21:06

ankit_m


People also ask

How do you wait in redux Saga?

You need to do something - as written this will call sleep (returning a promise) and then immediately throw it away! If you yield a call() then redux-saga will wait for the promise to resolve, e.g.: yield call(sleep, 2) . The best solution is in the answer above - using the delay utility function.

Is redux Saga overkill?

Once you start using one of these libraries, you will find that on the vast majority of projects, Redux is overkill. When the data fetching/caching part of your app is taken care of, there is very little global state for you to handle on the frontend.

Is redux Saga obsolete?

Such a powerful & elegant tool as Redux-Saga, a Redux side effect manager, is said to be deprecated, and no longer being maintained, starting from Jan 27, 2021.

How do sagas work redux?

Redux Saga is a middleware library used to allow a Redux store to interact with resources outside of itself asynchronously. This includes making HTTP requests to external services, accessing browser storage, and executing I/O operations. These operations are also known as side effects.


2 Answers

Yes, there is. You can use take to achieve this.

function *saga_b(action) {
  ...

  yield take('action_a') // this will put the saga_b essentially on hold until `action_a` is handled by the reducer

  ...
}

UPDATE

You can use saga-toolkit in order to put and wait for actions without take-ing them:

const resultOfFetchSomething = yield putAsync(fetchSomething()) // dispatches action "fetchSomething" & wait for the saga that is attached to it to finish running
like image 173
haxpanel Avatar answered Sep 20 '22 12:09

haxpanel


The way I do it my code bases is by calling the other saga directly. It unfortunately couples the two together, but since you need to wait the coupling will at least be more explicit.

function *saga_b(action) {
  yield put(..action3..)
  yield call(saga_a, action_a)
  yield put(..action4..)
}
like image 44
ctlevi Avatar answered Sep 17 '22 12:09

ctlevi