UNPKG

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