Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>
}
}
@chenglou

This comment has been minimized.

Copy link

chenglou commented Oct 28, 2017

The explanation: there are two bugs potential bugs, not present here because it's done :

@jordwalke

This comment has been minimized.

Copy link

jordwalke commented Nov 2, 2017

Great example. Maybe it should be documented somewhere more visible for anyone attempting to bridge subscriptions systems. It acts as a thorough checklist.

@sophiebits

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner Author

sebmarkbage commented Feb 22, 2018

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

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.