Question

How do I use a client side reconnection event in Meteor.

On the client, Meteor.apply takes a new wait option, which ensures that no further method calls are sent to the server until this method is finished; it is used for login and logout methods in order to keep the user ID well-defined. You can also specifiy an onReconnect handler which is run when re-establishing a connection; Meteor Accounts uses this to log back in on reconnect.

Can someone provide an example.

Here's the example in the accounts package.

  Accounts._makeClientLoggedIn = function(userId, token) {
    Accounts._storeLoginToken(userId, token);
    Meteor.default_connection.setUserId(userId);
    Meteor.default_connection.onReconnect = function() {
      Meteor.apply('login', [{resume: token}], {wait: true}, function(error, result) {
        if (error) {
          Accounts._makeClientLoggedOut();
          throw error;
        } else {
          // nothing to do
        }
      });
    };
    userLoadedListeners.invalidateAll();
    if (currentUserSubscriptionData) {
      currentUserSubscriptionData.handle.stop();
    }
    var data = currentUserSubscriptionData = {loaded: false};
    data.handle = Meteor.subscribe(
      "meteor.currentUser", function () {
        // Important! We use "data" here, not "currentUserSubscriptionData", so
        // that if we log out and in again before this subscription is ready, we
        // don't make currentUserSubscriptionData look ready just because this
        // older iteration of subscribing is ready.
        data.loaded = true;
        userLoadedListeners.invalidateAll();
      });
  };

I assume you can't just define another default_connection.onReconnect if you want the accounts one to still work?

Thanks.

Edit:

Thinking about it a bit more, instead of using onReconnect are you perhaps supposed to use Meteor.status() instead?

Was it helpful?

Solution

Harry, I saw your comment above and made this change. I think you are correct. Because Meteor.status is a reactive variable, this will re-run anytime the connection status changes.

if (Meteor.isClient) {
    Tracker.autorun(function () {
        if (Meteor.status().connected) {
            console.log("connected");
        } else {
            console.log("disconnected");
        }
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top