Search code examples
reduxredux-sagaredux-actions

Can I bind an argument value ahead of time when using redux-actions?


I have an action and a saga.

I want to supply a value to the action instance from inside actions.js.

I also want to supply a value to the action instance from inside the saga.

So when the reducer associated with the action is called, it receives two values in the payload.

How can I do this?

actions.js

import { createAction } from 'redux-actions';
export const myAction = createAction('ACTION_NAME'); // How do I supply payload value "foo" here?

sagas.js

function* mySaga({
    yield put(myAction()); // How do I supply  payload value "bar" here?
}

reducers.js

export default handleActions({ 
  'ACTION_NAME': handleReduce(state, { payload: { foo, bar } }) => 
     { /* foo and bar should be defined */ }) });

Solution

  • When you create an action you can add any payload to it you want. Now you just creating action with bare string and no payload.

    createAction(type, payloadCreator)

    payloadCreator must be a function, undefined, or null

    createAction('ACTION_NAME', () => { reuturn {foo: 'bar'}; })

    https://github.com/reduxactions/redux-actions/blob/master/docs/api/createAction.md#createactiontype-payloadcreator-createactiontype-payloadcreator

    in sagas put accepts bare object with type (string) and payload too

    E.g. yield put({ type: 'PRODUCTS_RECEIVED', products })

    So if createAction returns object with type and payload, it will be used by sagas too. You can use console.log before yeld to check what your action creator returns.

    console.log('Action for saga:', myAction());    
    yield put(myAction()); // How do I supply  payload value "bar" here?