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

@ -7,40 +7,52 @@ function observe(WrappedComponent) {
observedValues: {}, observedValues: {},
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({
observedValues: {
...this.state.observedValues,
[prop]: value
}
});
},
err => {
// TODO: pass the error to the wrapped component
console.err(err);
}
);
this.setState({ this.setState({
subscriptions: { observedValues: {
...this.state.subscriptions, ...this.state.observedValues,
[prop]: subscription [prop]: value
} }
}); });
},
err => {
// TODO: pass the error to the wrapped component
console.err(err);
}
);
this.setState({
subscriptions: {
...this.state.subscriptions,
[prop]: subscription
} }
}); });
} }
componentDidMount() {
Object.keys(this.props).forEach(this.subscribeToProp);
}
componentWillUnmount() { componentWillUnmount() {
this.state.subscriptions.forEach(subscription => { this.state.subscriptions.forEach(subscription => {
subscription.unsubscribe(); subscription.unsubscribe();
}); });
} }
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} />;