Last active
February 9, 2019 14:10
-
-
Save hckhanh/7370bf33331893e338bfc2a72e151103 to your computer and use it in GitHub Desktop.
Implementation for HOC
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
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