Search code examples
vue.jsmeteor

vue-meteor-tracker not fetching current user


I am new to both Vuejs and Meteorjs so please excuse if these are newbie questions or the syntax is off. I am trying to use vue-meteor-tracker to update the login\register button to logout but I am unable to do so. The Meteor.user always comes as undefined. What am I missing?

base.js:

    import { Meteor } from 'meteor/meteor';
export default {
      meteor: 
      {
        $lazy: true,
        $subscribe: 
        {
          'currentUser': function() {
            return Meteor.user();
          },
      'currentUserId': function() {
        return Meteor.userId();
      }
        },
      },
    }

plugins.js

import VueMeteorTracker from 'vue-meteor-tracker';
Vue.use(VueMeteorTracker);

MainNavBar.vue

<li v-if="($parent.currentUserId==null)">
  <router-link v-bind:to="{ name: 'register' }">Register</router-link></li>
<li v-else>
  <router-link v-bind:to="{ name: 'register' }">Log out</router-link></li>
<script>
import base from '../base';
export default 
{  
  extends: base,  
  components:{
  },
  mounted() 
  {
    console.log(this.$parent.currentUserId);
  }
}
</script>

Login.Vue:

<script>
import '../api/methods.js';
import { Meteor } from 'meteor/meteor';
import base from './base';
export default
{
extends: base,
methods: 
  { 
    LoginUserForDomain() 
    {
      Meteor.call('loginUserForDomain', this.user.email, this.user.password, this.user.domain, 
        (error, result) => 
        {
          if(result && result.userId && result.domain) 
          {                 
            Meteor.loginWithPassword(email, password);
            this.$router.push({ name: 'dashboard', params: { domain: result.domain }});                   
            return;
          }
        }
        );
    },
  },

Solution

  • As per my reply in the Meteor forums, you are $subscribing to currentUser and currentUserId instead of defining them as reactive data. Also, you don't need to publish/subscribe to the current user's userId because it is always available in the client as Meteor.userId().

    Meteor.userId() is a reactive data source and you can convert it into a Vue reactive property using vue-meteor-tracker like this: e.g. within App.vue:

    <script>
    import { Meteor } from 'meteor/meteor';
    export default {
      meteor: {
        currentUserId() {
          return Meteor.userId();
        },
      },
    }
    </script>
    

    Then you can use it within any template as, e.g. v-if="$root.currentUserId", or within any component's code as this.$root.currentUserId.

    In this simple example I have used the root Vue instance as an easily accessible global data store, but it's more widely accepted to use a dedicated data store, or use Vuex.