Last active
October 28, 2018 05:57
-
-
Save ryardley/7f75d1f848607da523609f26b939ee45 to your computer and use it in GitHub Desktop.
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
// 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} />; | |
} | |
}; | |
} |
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 CommentListWithSubscription = withSubscription( | |
CommentList, | |
(DataSource) => DataSource.getComments() | |
); | |
const BlogPostWithSubscription = withSubscription( | |
BlogPost, | |
(DataSource, props) => DataSource.getBlogPost(props.id) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment