Reputation: 667
Can someone explain this thing to me: if I'm getting data from a collection in browser's console, it works fine, but at the same time when a template (which uses the same collection) is being rendered it throws an exception as the query result is empty. What am I doing wrong?
Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
var hubName = 'foo',
thread = Session.get("currentThread"),
hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
return hub.threads[thread].posts;
}
//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]
Other templates that use the same collection work fine, though
Upvotes: 0
Views: 131
Reputation: 75945
When Meteor initially loads on the browser it wont yet have the data from the collections from the server.
It takes a very short amount of time for them to be available. So you just need to handle the case where there is no result provided. When the data arrives reactivity should update all your templates with the new data.
You can use something like:
hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;
findOne
is a shorter version of find().fetch[0]
. So if there isn't a result i.e null
nothing is returned and .threads
wont be read so there wouldn't be an exception.
Upvotes: 1