UNPKG

2.18 kBJavaScriptView Raw
1import warning from './utils/warning';
2
3function bindActionCreator(actionCreator, dispatch) {
4 return function () {
5 return dispatch(actionCreator.apply(undefined, arguments));
6 };
7}
8
9/**
10 * Turns an object whose values are action creators, into an object with the
11 * same keys, but with every function wrapped into a `dispatch` call so they
12 * may be invoked directly. This is just a convenience method, as you can call
13 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
14 *
15 * For convenience, you can also pass a single function as the first argument,
16 * and get a function in return.
17 *
18 * @param {Function|Object} actionCreators An object whose values are action
19 * creator functions. One handy way to obtain it is to use ES6 `import * as`
20 * syntax. You may also pass a single function.
21 *
22 * @param {Function} dispatch The `dispatch` function available on your Redux
23 * store.
24 *
25 * @returns {Function|Object} The object mimicking the original object, but with
26 * every action creator wrapped into the `dispatch` call. If you passed a
27 * function as `actionCreators`, the return value will also be a single
28 * function.
29 */
30export default function bindActionCreators(actionCreators, dispatch) {
31 if (typeof actionCreators === 'function') {
32 return bindActionCreator(actionCreators, dispatch);
33 }
34
35 if (typeof actionCreators !== 'object' || actionCreators === null) {
36 throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
37 }
38
39 var keys = Object.keys(actionCreators);
40 var boundActionCreators = {};
41 for (var i = 0; i < keys.length; i++) {
42 var key = keys[i];
43 var actionCreator = actionCreators[key];
44 if (typeof actionCreator === 'function') {
45 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
46 } else {
47 warning('bindActionCreators expected a function actionCreator for key \'' + key + '\', instead received type \'' + typeof actionCreator + '\'.');
48 }
49 }
50 return boundActionCreators;
51}
\No newline at end of file