Search code examples
meteoriron-router

Helper variable undefined from router data


I'm retrieving a Collection document based on a Session variable, and then passing this as a variable called store through an iron:router data context. The problem is that it sometimes returns undefined, as if it had not prepared itself in time for the helper to execute. How do I ensure the variable is always defined before the helper/template runs?

Here's my route, you can see that the data context includes retrieving a doc from a collection based on an _id stored in a Session variable:

Router.route('/sales/pos', {
    name: 'sales.pos',
    template: 'pos',
    layoutTemplate:'defaultLayout',
    loadingTemplate: 'loading',
    waitOn: function() {
        return [
            Meteor.subscribe('products'),
            Meteor.subscribe('stores'),
            Meteor.subscribe('locations'),
            Meteor.subscribe('inventory')
        ];
    },
    data: function() {
        data = {
            currentTemplate: 'pos',
            store: Stores.findOne(Session.get('current-store-id'))
        }
        return data;
    }
});

And here is the helper which relies on the store variable being passed to the template:

Template.posProducts.helpers({
    'products': function() {
        var self = this;
        var storeLocationId = self.data.store.locationId;

        ... removed for brevity ...
        return products;
    }
});

Solution

  • This is a common problem in Meteor. While you wait on your subscriptions to be ready, this does not mean your find function had time to return something. You can solve it with some defensive coding:

    Template.posProducts.helpers({
      'products': function() {
        var self = this;
        var storeLocationId = self.data.store && self.data.store.locationId;
        if (storeLocationId) {
          ... removed for brevity ...
          return products;
        }
      }
    });