Last active
January 22, 2018 11:53
-
-
Save matheusho/ac60612db4d70fafb05df9e439105ca6 to your computer and use it in GitHub Desktop.
Workaround to connect actions and state without redux and react-redux library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
const bindActionCreator = (dispatch, actionCreator) => { | |
return () => dispatch(actionCreator.apply(this, arguments)) | |
} | |
const bindActionCreators = (actions, dispatch) => { | |
const keys = Object.keys(actions) | |
const boundActionCreators = {} | |
if (typeof actions !== 'object' || actions === null) { | |
throw new Error(`actions expected an object or a function.`) | |
} | |
keys.forEach((key) => { | |
const actionCreator = actions[key] | |
if (typeof actionCreator === 'function') { | |
boundActionCreators[key] = bindActionCreator(dispatch, actionCreator) | |
} | |
}) | |
return boundActionCreators | |
} | |
export default (store, actions = {}) => { | |
const INITIAL_ACTION = { type: 'default' } | |
const INITIAL_STATE = store(undefined, { action: INITIAL_ACTION }) | |
return (Component) => ( | |
class extends React.Component { | |
constructor() { | |
super() | |
this.state = INITIAL_STATE | |
this.dispatch = this.dispatch.bind(this) | |
} | |
dispatch (action) { | |
if (typeof action === 'function') { | |
throw new Error(`Action expected an object.`) | |
// Improvement or async logics | |
// const getState = () => this.state | |
// return action(this.dispatch, getState, arguments) | |
} else { | |
this.setState(prevState => store(prevState, action)) | |
} | |
} | |
render () { | |
const boundActions = bindActionCreators(actions, this.dispatch) | |
return ( | |
<Component | |
{...boundActions} | |
{...this.state} | |
/> | |
) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment