Skip to content

Instantly share code, notes, and snippets.

@Jahans3
Last active February 23, 2019 14:18
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 Jahans3/69a58b95452c53e8f2e1a969c62396eb to your computer and use it in GitHub Desktop.
Save Jahans3/69a58b95452c53e8f2e1a969c62396eb to your computer and use it in GitHub Desktop.
Dispatch with async support
export class StateProvider extends React.PureComponent {
static defaultProps = {
state: {},
reducers: [],
middleware: []
};
state = this.props.state;
_dispatch = action => {
if (typeof action === 'function') {
return action(this._dispatch, this.state);
}
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>
);
}
}
@marcomarchiaro
Copy link

marcomarchiaro commented Feb 23, 2019

I tried to create a simple middleware function, probably I made a mistake but could ask you if you can give me a simple example?
For example:
The middleware function have to return a function? is correct?
export function countMiddleware (state:ICounter,action: IActionType) {
if (action.type === ADD_N) {
return dispatch(sideEffectFunction());
}
}

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