Skip to content

Instantly share code, notes, and snippets.

@Jahans3
Last active December 5, 2018 15:41
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/f42a8adee1c7072894bc5d37fe5dcbd3 to your computer and use it in GitHub Desktop.
Save Jahans3/f42a8adee1c7072894bc5d37fe5dcbd3 to your computer and use it in GitHub Desktop.
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