gameFrenzy07
gameFrenzy07

Reputation: 397

How to execute an action after the first one is resolved in saga?

I am working on a project that uses React, Redux-Saga. In my code, I have to call same action twice. I want to execute them one after the other. But what happens is that, both of them are called at once because they are essentially non-blocking and in the saga-selectors, it only resolves the first action that reaches it. How can i change this behavior in my react component from where these actions are called? I can't make changes in saga because i don't know it enough and i am only dealing with react. Please guide me!!!

I tried to use setTimeout(), but silly me it won't work because the functions are non blocking in nature.

let body = {}

body = {
  uuid: dragRow.uuid,
  orderId: hoverRowId
}
console.log("update for: ", dragRow)
this.props.updateSection(body);


body = {
  uuid: hoverRow.uuid,
  orderId: dragRowId
}
console.log("update for: ", hoverRow);
this.props.updateSection(body);

This is the code for saga:

//UPDATE SECTION
function* updateSection(sectionAction) {
try {
    const payload = yield call(Api.updateSection, sectionAction.payload);
    yield put({ type: sectionAction.type + "_success",payload: payload });
} catch (error) {
    yield put({ type: sectionAction.type + "_failed", error })
    }
}

function* watchUpdateSection() {
    yield takeLeading([sectionConstants.UPDATE_SECTION, sectionConstants.HIDE_SECTION, sectionConstants.PUBLISH_SECTION], updateSection)
}

Expected is that the first function call to updateSection() resolves and only after that my second call to it is passed. Right now both of them try to execute at once and only the leading one is executed.

Upvotes: 1

Views: 3764

Answers (1)

azundo
azundo

Reputation: 6052

For synchronous execution you can use an actionChannel: https://redux-saga.js.org/docs/advanced/Channels.html

import { take, actionChannel, call, ... } from 'redux-saga/effects'

function* watchUpdateSection() {
  // create a channel that is buffered with actions of these types
  const chan = yield actionChannel([
    sectionConstants.UPDATE_SECTION,
    sectionConstants.HIDE_SECTION,
    sectionConstants.PUBLISH_SECTION,
  ]);
  while (true) {
    // take from the channel and call the `updateSection` saga, waiting
    // for execution to complete before taking from the channel again
    const action = yield take(chan);
    yield call(updateSection, action);
  }
}

Upvotes: 2

Related Questions