1 | import { kindOf } from './utils/kindOf'
|
2 |
|
3 | function bindActionCreator(actionCreator, dispatch) {
|
4 | return function () {
|
5 | return dispatch(actionCreator.apply(this, 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 an action creator as the first argument,
|
16 | * and get a dispatch wrapped 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 | */
|
30 | export 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(
|
37 | `bindActionCreators expected an object or a function, but instead received: '${kindOf(
|
38 | actionCreators
|
39 | )}'. ` +
|
40 | `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
|
41 | )
|
42 | }
|
43 |
|
44 | const boundActionCreators = {}
|
45 | for (const key in actionCreators) {
|
46 | const actionCreator = actionCreators[key]
|
47 | if (typeof actionCreator === 'function') {
|
48 | boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
|
49 | }
|
50 | }
|
51 | return boundActionCreators
|
52 | }
|