javascriptreactjsmeteormeteor-accounts

how to sync pages after logout and login on one of them?


After logout and login I try to click something on another page but see endless spinner due to userId null. How to sync Meteor.userId after changing user? ON server side:

Meteor.publish('myPublish', function () {
if (!this.userId) {
  return this.ready();
}
return Collection.find();});

On client side:

const handles = [
    Meteor.subscribe('settings')
  ];
  const loading = handles.some(handle => !handle.ready());

Solution

  • The Meteor.userId function is a reactive datasource, which allows you to autorun a Tracker and subscribe, when the userId is there.

    Classic Meteor code would look like this:

    Tracker.autorun(() => {
      if (Meteor.userId() && Meteor.user()) {
        Meteor.subscribe('settings') // will only execute, once the user is logged in
      }
    })
    

    For React you use withTracker and should include the Meteor.userId to your bindings:

    export default withTracker(({ id }) => {
      const userId = Meteor.userId()
      const handles = userId && [
        Meteor.subscribe('todos.inList', id),
        Meteor.subscribe('otherSub'),
      ];
      const loading = !userId || handles.some(handle => !handle.ready());
      return {
        loading,
      };
    })(MyComponent);
    

    The call to Meteor.userId should activate the internal Tracker computation to re-run a cycle, once it returns a different value (a non-null value, once logged in).

    You can also use Meteor.loggingIn as reactive data source:

    export default withTracker(({ id }) => {
      const loggingIn = Meteor.loggingIn()
      const handles = !loggingIn && [
        Meteor.subscribe('todos.inList', id),
        Meteor.subscribe('otherSub'),
      ];
      const loading = loggingIn || handles.some(handle => !handle.ready());
      return {
        loading,
      };
    })(MyComponent);
    

    References:

    https://docs.meteor.com/api/tracker.html#Tracker-autorun

    https://guide.meteor.com/react.html#using-withTracker

    https://docs.meteor.com/api/accounts.html#Meteor-userId

    https://docs.meteor.com/api/accounts.html#Meteor-loggingIn