How to get action.params from saga

11,626

Solution 1

const actionCreator=()=>({
  type: 'MY_ACTION',
  status:true
})

 function* updatePorts(action) {
  console.log(action.status)
}

function* watchUpdatePorts() {
  yield* takeEvery('MY_ACTION', updatePorts)
}

https://github.com/redux-saga/redux-saga/tree/master/docs/api#takeeverypattern-saga-args

Solution 2

const actionCreator = () => ({
  type: 'MY_ACTION',
  status: true
})

function* updatePorts() {
  while (true) {
      const { status } = take('MY_ACTION');
      // ...
  }

}

You could also do something like this. The redux-saga docs have a nice explanation on the advantages:

Using take has a subtle impact on how we write our code. In the case of takeEvery the invoked tasks have no control on when they'll be called. They will be invoked again and again on each matching action. They also have no control on when to stop the observation.

In the case of take the control is inverted. Instead of the actions being pushed to the handler tasks, the Saga is pulling the action by itself. It looks as if the Saga is performing a normal function call action = getNextAction() which will resolve when the action is dispatched.

read more here: https://redux-saga.js.org/docs/advanced/FutureActions.html

Share:
11,626
Amio.io
Author by

Amio.io

Updated on June 04, 2022

Comments

  • Amio.io
    Amio.io about 2 years

    I am using redux-saga. In the code yield* ReduxSaga.takeEvery('MY_ACTION', updatePorts); how can I access the action to get its fields.

    For example I have an action creator:

    function status(){
      type: 'MY_ACTION',
      status: true
    } 
    

    How can I access action.status from my saga? Or do I have to access data only via getState() and select?

  • Amio.io
    Amio.io almost 8 years
    You are awesome. It's working. Can you please post a link to documentation. I could have found it.
  • digit
    digit over 6 years
    Working for me. Awesome dude!