I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:
Games = new Meteor.Collection("games");
if (Meteor.isClient) {
Meteor.startup(function() {
console.log(Games.findOne({}));
});
}
This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?
Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.
You should first publish
the data from the server.
if(Meteor.isServer) {
Meteor.publish('default_db_data', function(){
return Games.find({});
});
}
On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe
calls.
if (Meteor.isClient) {
Meteor.startup(function() {
Session.set('data_loaded', false);
});
Meteor.subscribe('default_db_data', function(){
//Set the reactive session as true to indicate that the data have been loaded
Session.set('data_loaded', true);
});
}
Now when you perform collection queries, you can check if the data is loaded or not as:
if(Session.get('data_loaded')){
Games.find({});
}
Note: Remove autopublish
package, it publishes all your data by default to the client and is poor practice.
To remove it, execute $ meteor remove autopublish
on every project from the root project directory.
Use DDP._allSubscriptionsReady()
(Meteor 0.7)
As of Meteor 1.0.4, there is a helper that tells you exactly when a particular subscription is ready: Template.instance().subscriptionsReady()
.
Since this question is a duplicate, please check my answer in the original question, Displaying loader while meteor collection loads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With