Skip to content

Instantly share code, notes, and snippets.

@hckhanh
Last active February 9, 2019 14:10
Show Gist options
  • Save hckhanh/7370bf33331893e338bfc2a72e151103 to your computer and use it in GitHub Desktop.
Save hckhanh/7370bf33331893e338bfc2a72e151103 to your computer and use it in GitHub Desktop.
Implementation for HOC
import React, { Component } from "react";
import DataSource from "../DataSource";
export default function withSubscription(Component, selectData) {
return class extends Component {
constructor(props) {
super(props);
this.state = {
data: selectData(DataSource, props)
};
}
componentDidMount() {
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange = () => {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
return <Component data={this.state.data} {...this.props} />;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment