Skip to content

Instantly share code, notes, and snippets.

@matheusho
Last active January 22, 2018 11:53
Show Gist options
  • Save matheusho/ac60612db4d70fafb05df9e439105ca6 to your computer and use it in GitHub Desktop.
Save matheusho/ac60612db4d70fafb05df9e439105ca6 to your computer and use it in GitHub Desktop.
Workaround to connect actions and state without redux and react-redux library
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