Search code examples
firebasevue.jsvuefire

How to get the user info to the "data" part of the app in vue.js?


Would you happen to know how to set the user to the currentUser? I am using vuefire and firebase. The user.uid is returning undefined.

 <td v-if="(building['key'] && building['key'].child('ownerId')) == user.uid">
            <p >{{building['.key']}} + {{user.uid}}</p>
</td>

this is the rest of my code:

import firebase,{ db, usersRef, buildingsRef } from '../firebase-config';
import { store } from '../store/store';

export default {

  firebase() { 
    // from my understanding this just gives me a quick access to the Refs and a short nomenclature
    return { 
    users: usersRef,  
    buildings: buildingsRef, 
    }
  },
  name: 'buildings',
  data () {
    return {
      user: "",
      building: {
        name: '',
        address: '',
        comments: '',
        ownerId: '',
      },
    }
  },

I am trying to do it through the store in the beforeCreate hook:

  beforeCreate () {
       this.$store.dispatch('setUser');
       let user = this.$store.getters.getUser;
       console.log(user); // this works!!!
      this.$set(this.user, 'uid', user.uid )
  }   
},

If instead I set the user in create hook like this:

  created () {
       this.$store.dispatch('setUser');
       let user = this.$store.getters.getUser;
       console.log(user); // this works!!!
      this.$set(this.user, 'uid', user.uid )
    } 

I get this error:

enter image description here


Solution

  • In Vue, the state (aka data properties) is initialized between the beforeCreate and created hooks.

    So any change you do to data in beforeCreate is lost.

    Change your hook to created

    created() {                         // changed this line
      this.$store.dispatch('setUser');
      let user = this.$store.getters.getUser;
      console.log(user); // this works!!!
      this.$set(this.user, 'uid', user.uid)
    }