Instantly share code, notes, and snippets.

@Jahans3 Jahans3/connect-state.js
Last active Dec 5, 2018

Embed
What would you like to do?
State consumer
class ConnectState extends React.Component {
state = this.props.mapState(this.props.state);
static getDerivedStateFromProps (nextProps, nextState) {}
shouldComponentUpdate (nextProps) {
if (!Object.keys(this.state).length) {
this.setState(this.props.mapDispatch(this.props.state));
return true;
}
console.log({
s: this.state,
nextState: nextProps.mapState(nextProps.state),
state: this.props.mapState(this.state)
});
return false;
}
render () {
return this.props.children({ state: this.props.state, dispatch: this.props.dispatch });
}
}
export function StateConsumer ({ mapState, mapDispatch, children }) {
return (
<StateContext.Consumer>
{({ state, dispatch }) => (
<ConnectState state={state} dispatch={dispatch} mapState={mapState} mapDispatch={mapDispatch}>
{children}
</ConnectState>
)}
</StateContext.Consumer>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment