Do I need to 'unsubscribe'?


#1

I have a Meteor app with a React front end and FlowRouter and I’m having some issues with my subscriptions.

Let’s say I have a collection of leads and leads can be grouped by campaigns. If I subscribe to all leads on page A like so:

getMeteorData() {
  const leadsSubHandle = Meteor.subscribe('leads', {limit: 50});
  return {
    leads: Collections.Leads.find({}, { sort: { createdAt: -1 } }).fetch(),
    leadsLoading: ! leadsSubHandle.ready()
  };
}

Then I can view them just fine using a ‘dumb’ component called LeadsList which in turn renders LeadRow for each lead.

I have another page that scopes the leads to a campaign. The subscriptions look like this:

getMeteorData() {
  const campaignId = FlowRouter.current().params['id'];
  const campaignHandle = Meteor.subscribe('campaignWithTemplate', campaignId);
  const leadsHandle = Meteor.subscribe('leadsForCampaign', campaignId, {
    limit: 50,
    page: this.state.page
  });

  return {
    currentUser: Meteor.user(),
    campaign: Collections.Campaigns.findOne(),
    template: Collections.Templates.findOne(),
    leads: Collections.Leads.find().fetch(),
    loading: ! campaignHandle.ready(),
    leadsLoading: ! leadsHandle.ready()
  };
}

This data then gets rendered using the same dumb LeadsList and LeadsRow components as before. However, the subscription on this second page only works if I do a full reload of the page (i.e. CMD+R). If I hit the page via a FlowRouter link, the subscription doesn’t get updated to only the leads for the campaign. I can see from logging the prop passed to LeadsList that almost all the leads are still there.

So I feel like I should be checking to see when my first component becomes unmounted and unsubscribe to all the leads there so that when the ‘resubscribe’ happens it’s ‘clean’. That seems a bit unintuitive though. Should that happen automatically?

Any help appreciated!


#2

unsubscribe happens automatically. It has nothing to do with it. This might be a FlowRouter problem I don’t know.


#3

do you render that component only after all subscriptions are in Ready status ?


#4

Thanks for the input gents.

It turned out that the issue was in my publications. I was publishing more data than I should have been. When switching pages via FlowRouter there momentarily was more data available on the client than I was expecting.

For example, page 1 has 10 leads and page two scopes the same data using the campaignId to, say, only a single lead. When rendering the second page from the first (via FlowRouter), it was initially trying to render with 10 leads rather than 1. This caused an error because I was attempting to iterate the data and render it but some properties were missing.

I’m still not 100% sure on how/why this was happening but ensuring that the published data selectors matched up with the queries seems to have fixed it.