Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Last active October 11, 2020 23:46
Show Gist options
  • Save sebmarkbage/a2ed9dc5146604b7a122d446b0987cb2 to your computer and use it in GitHub Desktop.
Save sebmarkbage/a2ed9dc5146604b7a122d446b0987cb2 to your computer and use it in GitHub Desktop.
Subscription Is Hard?
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>
}
}
@bvaughn
Copy link

bvaughn commented Feb 28, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment