Redux: feature request: allow bindActionCreators to accept array

Created on 10 Jun 2016  ·  3Comments  ·  Source: reduxjs/redux

Currently, bindActionCreators accepts a single function or an object of functions. It would be useful if it accepted an array as well, to aid this code pattern:

import * as ac from './actionCreators';

// later in file...
const [doThis, doSomethingElse, doAnotherThing] = bindActionCreators(
  [ac.doThis, ac.doSomethingElse, ac.doAnotherThing
], dispatch);
// ...

I like to specify my creator names explicitly because any mistakes are caught immediately by eslint-plugin-import/namespace as an error.

I believe this is the necessary change:

diff --git a/src/bindActionCreators.js b/src/bindActionCreators.js
index e70e270..6050c32 100644
--- a/src/bindActionCreators.js
+++ b/src/bindActionCreators.js
@@ -28,6 +28,10 @@ export default function bindActionCreators(actionCreators, dispatch) {
     return bindActionCreator(actionCreators, dispatch)
   }

+  if (Array.isArray(actionCreators)) {
+    return actionCreators.map(ac => bindActionCreator(ac, dispatch));
+  }
+
   if (typeof actionCreators !== 'object' || actionCreators === null) {
     throw new Error(
       `bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +

Most helpful comment

I think making bindActionCreator more polymorphic would be too much, how about just creating a wrapping function that does this for you?

function mapBindActionCreators(actions, dispatch) {
  return actions.map(action => bindActionCreator(action, dispatch)
}

All 3 comments

I think making bindActionCreator more polymorphic would be too much, how about just creating a wrapping function that does this for you?

function mapBindActionCreators(actions, dispatch) {
  return actions.map(action => bindActionCreator(action, dispatch)
}

If you have an array of them you could reduce() the array into an object and pass that to bindActionCreator

Yea, I think we’d like to avoid supporting every possible permutation here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vraa picture vraa  ·  3Comments

ramakay picture ramakay  ·  3Comments

jbri7357 picture jbri7357  ·  3Comments

captbaritone picture captbaritone  ·  3Comments

olalonde picture olalonde  ·  3Comments