Created
August 22, 2018 12:34
-
-
Save OliverJAsh/0c7a6cd5e4846001400e0998728116cd to your computer and use it in GitHub Desktop.
Simple react-redux using React's new Context API
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
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> | |
); |
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 { 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