Where to subscribe to a publication so that it's accessible immediately?


#1

When a user visits my site, I need to immediately grab a tracking ID from their cookies, and access a TrackingIds collection.

Template.layout.onRendered(function () {
  debugger;
  let trackingId = Cookie.get('trackingId');

  if (trackingId) {
    let trackingInfo = TrackingIds.findOne(trackingId);

    if (trackingInfo) {
      Session.set('limitProductsTo', {
        slug: {
          $in: trackingInfo.slugs
        }
      });
    }
  }
  [...]

TrackingIds.findOne keeps returning null, even though I have this in /client/lib:

Meteor.startup(function () {
  Meteor.subscribe('trackingIds');
});

I thought things in lib were executed first, before everything else. I’m confused about where I need to subscribe to this publication so that all my templates can access it very early on, possibly even in onCreated.

Thanks!


#2

Have you considered using Template subscriptions, and then execute the dependent code on Template.subscriptionsReady ? Even if lib executes before your template renders, the subscription may take some time to be ready. I’ve started moving over to Template subscriptions to handle race conditions like this, where previously I would mostly handle this type of thing in Iron Router.
http://docs.meteor.com/#/full/Blaze-TemplateInstance-subscribe


#3

I literally just thought of this as your reply came up. :slight_smile: Sometimes I forget about Meteor’s reactive magic.