feat: subscribe to new observables

This commit is contained in:
Richard Ramos 2019-08-27 21:13:58 -04:00
parent d795abe5fd
commit 52695e5538
3 changed files with 36 additions and 23 deletions

View File

@ -48,7 +48,7 @@ class App extends React.Component {
return ( return (
<div> <div>
<button onClick={this.createTrx}>Create Trx</button> <button onClick={this.createTrx}>Create Trx</button>
{escrowObservable && <EscrowObservator escrow={escrowObservable} myCustomProperty="Test" />} <EscrowObservator escrow={escrowObservable} myCustomProperty="Test" />
</div> </div>
); );
} }

View File

@ -3,6 +3,7 @@ import observe from "./observe";
const Escrow = props => { const Escrow = props => {
const { escrow, myCustomProperty } = props; const { escrow, myCustomProperty } = props;
if(!escrow) return <p>Loading...</p>;
return ( return (
<ul> <ul>
<li> <li>

View File

@ -8,9 +8,9 @@ function observe(WrappedComponent) {
subscriptions: {} subscriptions: {}
} }
componentDidMount() { subscribeToProp = prop => {
Object.keys(this.props).forEach(prop => { if(!isObservable(this.props[prop])) return;
if(isObservable(this.props[prop])){
const subscription = this.props[prop].subscribe( const subscription = this.props[prop].subscribe(
value => { value => {
this.setState({ this.setState({
@ -33,7 +33,9 @@ function observe(WrappedComponent) {
} }
}); });
} }
});
componentDidMount() {
Object.keys(this.props).forEach(this.subscribeToProp);
} }
componentWillUnmount() { componentWillUnmount() {
@ -42,6 +44,16 @@ function observe(WrappedComponent) {
}); });
} }
componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach(prop => {
if(!prevProps[prop] && this.props[prop]){
this.subscribeToProp(prop);
}
});
// TODO: check if prevProps and currProps are different, and unsubscribe from prevProp
}
render() { render() {
return <WrappedComponent {...this.props} {...this.state.observedValues} />; return <WrappedComponent {...this.props} {...this.state.observedValues} />;
} }