Skip to content

Commit 3cfdd73

Browse files
committed
Merge pull request reduxjs#352 from michaelcontento/function-support-for-bindActionCreators
Allow `bindActionCreators` to be used with function as actionCreator
2 parents 0fc5802 + d92f08e commit 3cfdd73

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

src/utils/bindActionCreators.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import mapValues from '../utils/mapValues';
22

3+
function bindActionCreator(actionCreator, dispatch) {
4+
return (...args) => dispatch(actionCreator(...args));
5+
}
6+
37
/**
48
* Turns an object whose values are action creators, into an object with the
59
* same keys, but with every function wrapped into a `dispatch` call so they
610
* may be invoked directly. This is just a convenience method, as you can call
711
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
812
*
9-
* @param {Object} actionCreators An object whose values are action creator
10-
* functions. One handy way to obtain it is to use ES6 `import * as` syntax.
13+
* @param {Object|Function} actionCreators An object whose values are action
14+
* creator functions. One handy way to obtain it is to use ES6 `import * as`
15+
* syntax. It also supports binding only a single function.
1116
*
1217
* @param {Function} dispatch The `dispatch` function available on your Redux
1318
* store.
@@ -16,7 +21,11 @@ import mapValues from '../utils/mapValues';
1621
* action creator wrapped into the `dispatch` call.
1722
*/
1823
export default function bindActionCreators(actionCreators, dispatch) {
24+
if (typeof actionCreators === 'function') {
25+
return bindActionCreator(actionCreators, dispatch);
26+
}
27+
1928
return mapValues(actionCreators, actionCreator =>
20-
(...args) => dispatch(actionCreator(...args))
29+
bindActionCreator(actionCreator, dispatch)
2130
);
2231
}

test/utils/bindActionCreators.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,15 @@ describe('bindActionCreators', () => {
2626
{ id: 1, text: 'Hello' }
2727
]);
2828
});
29+
30+
it('should support wrapping a single function only', () => {
31+
const actionCreator = actionCreators.addTodo;
32+
const boundActionCreator = bindActionCreators(actionCreator, store.dispatch);
33+
34+
const action = boundActionCreator('Hello');
35+
expect(action).toEqual(actionCreator('Hello'));
36+
expect(store.getState()).toEqual([
37+
{ id: 1, text: 'Hello' }
38+
]);
39+
});
2940
});

0 commit comments

Comments
 (0)