Provider with middleware
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
export class StateProvider extends React.PureComponent { | |
static defaultProps = { | |
state: {}, | |
reducers: [], | |
middleware: [] | |
}; | |
state = this.props.state; | |
_dispatch = action => { | |
const { reducers, middleware } = this.props; | |
const continueUpdate = middleware.reduce((result, middleware) => { | |
return result !== null ? middleware(action, this.state) : result; | |
}, undefined); | |
if (continueUpdate !== null) { | |
const nextState = reducers.reduce((state, reducer) => { | |
return reducer(state, action) || state; | |
}, this.state); | |
this.setState(nextState); | |
} | |
}; | |
render () { | |
return ( | |
<StateContext.Provider value={{ state: this.state, dispatch: this._dispatch }}> | |
{this.props.children} | |
</StateContext.Provider> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment