Skip to content

Instantly share code, notes, and snippets.

@nrafter
Created May 25, 2017 14:40
Show Gist options
  • Save nrafter/6d29b37539c6a7ba2d092700592783d7 to your computer and use it in GitHub Desktop.
Save nrafter/6d29b37539c6a7ba2d092700592783d7 to your computer and use it in GitHub Desktop.
// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
// ...and returns another component...
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}
componentDidMount() {
// ... that takes care of the subscription...
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment