Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created August 22, 2018 12:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OliverJAsh/0c7a6cd5e4846001400e0998728116cd to your computer and use it in GitHub Desktop.
Save OliverJAsh/0c7a6cd5e4846001400e0998728116cd to your computer and use it in GitHub Desktop.
Simple react-redux using React's new Context API
const store = configureAndCreateReduxStore();
const { ReduxProvider, ReduxConsumer } = createReactRedux(store);
export const FormConnected: React.SFC<OwnProps> = ownProps => (
<ReduxConsumer>
{pipe(
({ state, dispatch }) => ({
...ownProps,
...mapStateToProps(state, ownProps),
dispatch,
}),
props => (
<Form {...props} />
),
)}
</ReduxConsumer>
);
import { Action, AnyAction, Store, Unsubscribe } from 'redux';
import React = require('react');
export const createReactRedux = function<S = any, A extends Action = AnyAction>(
store: Store<S, A>,
) {
const defaultValue = { dispatch: store.dispatch, state: store.getState() };
const context = React.createContext(defaultValue);
class ReduxProvider extends React.Component<{}, S> {
unsubscribe: Unsubscribe | undefined;
state = store.getState();
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
const state = store.getState();
this.setState(state);
});
}
componentWillUnmount() {
if (this.unsubscribe !== undefined) {
this.unsubscribe();
}
}
render() {
const { state } = this;
const { dispatch } = store;
return (
<context.Provider value={{ dispatch, state }}>
{this.props.children}
</context.Provider>
);
}
}
const ReduxConsumer = context.Consumer;
return { ReduxProvider, ReduxConsumer };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment