jdscosta91
jdscosta91

Reputation: 704

Uncaught TypeError in Meteor

I have this code:

Meteor.subscribe('practices');

Session.set('practice', 'Practice 1');

Template.laps_t.laps = function () {
  var obj = Practices.findOne({name: Session.get('practice')});
  return obj.lap_n;
};

And I'm getting an error: Uncaught TypeError: Cannot read property 'lap_n' of undefined.

I know that lap_n is in fact a property of obj.

I'm not using autosubscribe. Any ideas?

EDIT:

SOLVED. Thanks guys.

if(obj){ return obj.lap_n } like you said did the trick.

Upvotes: 2

Views: 614

Answers (2)

crapthings
crapthings

Reputation: 2485

you might have to wait until data arrive, so may be you can try to add

if obj
    return obj.lap_n
else
    return {
        lap_n: 0
    }

Upvotes: 0

Rahul
Rahul

Reputation: 12231

You should always check for existence of objects inside templates. The way this works is that the Template will be immediately executed upon pageload, possibly even before the subscription has retrieved the mongo data from the server, so in that case your obj will be undefined and will not have the property you expect. But since Templates are reactive, once the data is available, your Practices.findOne call will be re-evaluated and the template re-executed. And then it will work.

Upvotes: 2

Related Questions