Component level subscription, howto


#1

I am finally trying to make the switch from Blaze to React and am having troubles to understand one simple concept I used all over the place with Blaze: template level subscriptions. I think I understand how subscriptions are done withTracker, but none of the examples I have found so far show how to stop the subscription. I want to understand how the blaze pattern of subscribing to data in the onCreated hook of a template and the automatic stopping of the subscription when destroying the template is done in react.

Any pointers welcome.


#2

I believe the subscription is stopped when the component unmounts, so you may want to structure your app in such a way that components which are wrapped in withTracker get unmounted when their corresponding subscriptions are no longer needed.

Also, see below:



#3

You can always stop() a subscription using the handle Meteor.subscribe returns if you want to take it into you own hands.

The project https://github.com/jonathanazulay/react-meteor-subscribe seems dead, but it demonstrates a way how to do it with a HOC.


#4

Too much has changed in 3 years that I would want to use the react-meteor-subscribe wrapper.

I would have thought that the lifecycle method componentWillUnmount should be used to stop a subscription, but it doesn’t have access to the subscription handle created in the withTracker call


#5

Hi Jamgold,

As eicksl has pointed out, withTracker unsubcribes when the component is unmounted and it does it automatically so you dont have to worry about it.

If you want to unsubscribe manually I think you can pass the handler as a prop to the component and use handler.stop()

EX:

export default withTracker(({ id }) => {
  const handler = Meteor.subscribe('subscription', param);
  const loading = !handler.ready();

  return {
    handler,
    loading,
  };
})(YourComponent);

Let me know if this helps you.


#6

Thank you, @pmogollon. That helped a lot, particularly the hint about returning the handle.