Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: How can I tell when the database is ready?

Tags:

meteor

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.

like image 778
Derek Thurn Avatar asked Feb 28 '13 07:02

Derek Thurn


3 Answers

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.

like image 50
sohel khalifa Avatar answered Oct 21 '22 09:10

sohel khalifa


Use DDP._allSubscriptionsReady() (Meteor 0.7)

like image 29
Denis Gorbachev Avatar answered Oct 21 '22 10:10

Denis Gorbachev


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.

like image 6
Dan Dascalescu Avatar answered Oct 21 '22 09:10

Dan Dascalescu