Last active
October 11, 2020 23:46
-
-
Save sebmarkbage/a2ed9dc5146604b7a122d446b0987cb2 to your computer and use it in GitHub Desktop.
Subscription Is Hard?
This file contains 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
class SubscriptionDoneRight extends Component { | |
state = { | |
data: Store.read(props.id) | |
} | |
getDerivedStateFromProps(props, state) { | |
return { | |
data: Store.read(props.id), | |
}; | |
} | |
handleData = (data) => { | |
this.setState({ data }); | |
} | |
componentDidMount() { | |
this._subscription = Store.subscribe(this.props.id, this.handleData); | |
let currentData = Store.read(this.props.id); | |
if (this.state.data !== currentData) { | |
this.setState({ data: currentData }); | |
} | |
} | |
componentDidUpdate(oldProps) { | |
if (oldProps.id !== this.props.id) { | |
Store.unsubscribe(this._subscription); | |
this._subscription = Store.subscribe(this.props.id, this.handleData); | |
let currentData = Store.read(this.props.id); | |
if (this.state.data !== currentData) { | |
this.setState({ data: currentData }); | |
} | |
} | |
} | |
componentWillUnmount() { | |
Store.unsubscribe(this._subscription); | |
} | |
render() { | |
return <div>{this.state.data}</div> | |
} | |
} |
Updated with some fixes and removed prefetching for now since that requires a cache and is a bit complicated to get right on its own.
Cross-linking to https://gist.github.com/bvaughn/d569177d70b50b58bff69c3c4a5353f3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should this call
this.setState({data: sub.read(newProps.id)})
in componentWillReceiveProps?Also, would a store update that occurs in between render and cDM have any negative effects? I guess it depends on the relative priorities.