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