Created
September 26, 2017 11:11
-
-
Save tarjei/75bd8f8c5ac6d3fcf97a6fc8d0260dff to your computer and use it in GitHub Desktop.
Recompose withReducer + withHandlers but as a simple render function component.
This file contains hidden or 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, { 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} /> | |
}} | |
/> | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, this dispatch returns promises.