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 (
<div>
<button onClick={this.createTrx}>Create Trx</button>
{escrowObservable && <EscrowObservator escrow={escrowObservable} myCustomProperty="Test" />}
<EscrowObservator escrow={escrowObservable} myCustomProperty="Test" />
</div>
);
}

View File

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

View File

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