How to get action.params from saga
Asked Answered
S

3

13

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?

Schorl answered 27/7, 2016 at 6:36 Comment(0)
V
36
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

Violette answered 27/7, 2016 at 6:50 Comment(2)
You are awesome. It's working. Can you please post a link to documentation. I could have found it.Schorl
Working for me. Awesome dude!Disembarrass
H
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

Halvah answered 3/9, 2017 at 22:14 Comment(0)
C
0

Normally you may have a root saga or index saga and in that you can have a init generator with yield all to look like below:

//in your action creator
const actionCreator = () => ({
    type: 'MY_ACTION1',
    status: true
});
//in your saga file, you will receive 'action' and then you can destructure it to status if you want.
function* updateDataForAction1({ status }) {
    //use value of status 
}
//in your root saga file
export function* watchInit() {
    yield all([
        takeEvery('MY_ACTION1', updateDataForAction1),
        takeEvery('MY_ACTION2', updateDataForAction2),
        takeEvery('MY_ACTION3', updateDataForAction3),
    ]);
}
Cruise answered 29/3, 2018 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.