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>
}
}
@sophiebits
Copy link

sophiebits commented Nov 10, 2017

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.

@sebmarkbage
Copy link
Author

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.

@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