Skip to content

Instantly share code, notes, and snippets.

@tarjei
Created September 26, 2017 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarjei/75bd8f8c5ac6d3fcf97a6fc8d0260dff to your computer and use it in GitHub Desktop.
Save tarjei/75bd8f8c5ac6d3fcf97a6fc8d0260dff to your computer and use it in GitHub Desktop.
Recompose withReducer + withHandlers but as a simple render function component.
import React, { Component } from 'react'
import PropTypes from 'prop-types'
export default class LocalReducer extends Component {
static propTypes = {
handlers: PropTypes.object.isRequired,
mapPropsToInitialState: PropTypes.func.isRequired,
reducer: PropTypes.func.isRequired,
render: PropTypes.func.isRequired,
reducerKey: PropTypes.string
}
static defaultProps = {
reducerKey: 'state'
}
constructor(props) {
super(props)
this.handlers = {}
Object.keys(props.handlers).forEach(fnName => {
const fn = props.handlers[fnName]
this.handlers[fnName] = (...args) => {
return fn({
...this.props,
dispatch: this.dispatch,
[this.props.reducerKey]: this.state
})(...args)
}
})
this.state = props.mapPropsToInitialState(props)
this.reducer = props.reducer
}
dispatch = action => {
return new Promise((resolve, reject) => {
this.setState(
state => {
try {
return this.reducer(state, action)
} catch (e) {
console.error('LocalReducer:', e)
reject()
return state
}
},
() => {
resolve(this.state)
}
)
})
}
render() {
return this.props.render({
[this.props.reducerKey]: this.state,
handlers: this.handlers
})
}
}
/* usage
return (
<LocalReducer
reducer={quizReducer}
mapPropsToInitialState={mapPropsToInitialState}
handlers={handlers}
quiz={quiz}
render={({ state, handlers }) => {
return <QuizFrame quizContext={state} handlers={handlers} />
}}
/>
)
*/
@tarjei
Copy link
Author

tarjei commented Sep 26, 2017

Also, this dispatch returns promises.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment