Javascript: Redux: Dispatching Multiple Actions

Tiny musing for self amusement. And hopefully some edification?

Probably one of the first things anyone starting out on Redux wonders is, can you dispatch multiple actions?

The answer of course is, yes, just either call dispatch multiple times or iterate dispatch over an array. Usually, though, if you’re dispatching multiple actions like that, it’s a sign that you might want to look into creating yet another action to better encode the intent behind the cause of all those other actions.

But, what if your action is a strict combination of those other actions? Well, you could just create a meta-action which takes those other actions and returns a new single one representing them. Behind the scenes, of course, it’d still just iterate over the actions, dispatching them in turn.

There’s actually two ways we could go about this, both of them essentially equivalent in function:

  1. Use Redux Thunk
  2. Create our own middleware

Using Redux Thunk

Note: I’m presuming you know how to setup Redux Thunk’s middleware so I will be skipping that part. I’m also presuming you’re at least passingly familiar with some ES6 features such as arrow functions.

How would this look with a Thunk Action Creator, then?

Creating Our Own Middleware

Note: I’m presuming you know how to add middleware to your Redux Store, so I’m skipping that part.

What might a custom middleware look like?

Creating Our Own Middleware: Variation

As a variation on the above, you could just say “Screw it, I’mma teach Redux how to handle arrays!”, in much the same manner Redux Thunk teaches Redux how to handle Functions.

Result

The effective result is the same: you can now dispatch multiple actions from one dispatch call.

Here we have two examples using React Redux’s connect decorator and React’s JSX, the first using the multiAction action creator, the second using just an array.

Note: These examples use a Stateless Functional Component.

Bonus!

As mentioned at the very beginning, you could also just save a new action creator which explicitly encodes this combination of actions as a new one…

// multiAction style!
const doAllTheThings = () => multiAction([
doThisThing(),
doThatThing({ computer: 'over' }),
doTheOtherThing('foo'),
]);
// array style!
const doAllTheThings = () => [
doThisThing(),
doThatThing({ computer: 'over' }),
doTheOtherThing('foo'),
];

Then in connect

connect(
null,
dispatch => ({
doAllTheThings: () => dispatch(doAllTheThings()),
}),
)(...);

Nice.

As an added bonus, if it turns out later that just using an array of actions like that was not quite correct, or you need to change which actions are being used there, you how have that already decoupled from the view for easy refactor. Very nice.