@heygrady/

dispatchProps

ES6

An example of how the mapDispatchToProps argument of react-redux connect is used to create a dispatchProps object.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const GOOSE_HONK = 'GOOSE_HONK' // <-- action type
const honk = (payload) => ({ type: GOOSE_HONK, payload }) // <-- action creator

const createActionDispatcher = (dispatch, actionCreator) => (
  (...payload) => dispatch(actionCreator(...payload)) // <-- action dispatcher
)

const mapDispatchToProps = (dispatch) => {
  const dispatchProps = {
    onClick: createActionDispatcher(dispatch, honk) // <-- map action dispatcher to onClick prop
  }
  return dispatchProps
}

const dispatch = (action) => console.log(action) // <-- fake dispatch

// normally, this would happen when connect is initialized
const dispatchProps = mapDispatchToProps(dispatch)

console.log(dispatchProps)
// logs --> { onClick: [Function: actionDispatcher] }

// normally, this would happen within a react component
const event = { type: 'SyntheticEvent' } // <-- fake event

dispatchProps.onClick(event)
// logs --> { type: 'GOOSE_HONK', payload: { type: 'SyntheticEvent' } }

// notice that this has the same effect
const action = honk(event)
console.log(action)
// logs --> { type: 'GOOSE_HONK', payload: { type: 'SyntheticEvent' } }
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie