简体   繁体   中英

Get data from Firebase in Vue.js component

I'm starting my first serious app with Vue.js and I have an issue gathering data from Firabase. The idea here is simply to get data linked to an user ID. My first though was to store that in a computed value, like so

export default {

  ...

  computed: {
    userInfo: function() {
      const firestore = firebase.firestore();
      const docPath = firestore.doc('/users/' + firebase.auth().currentUser.uid);

      docPath.get().then((doc) => {
        if (doc && doc.exists) {
          return doc.data();
        }
      });
    }
  }
}

But, when I try to access this variable, it's undifined .

My guess is that the value is computed before the asynchronous call has ended. But I can't see how to get around it.

Indeed you have to take into account the asynchronous character of the get() method. One classical way is to query the database in the created hook, as follows:

export default {

  data() {
    return {
      userInfo: null,
    };
  },

  ....

  created() {
      const firestore = firebase.firestore();
      const docPath = firestore.doc('/users/' + firebase.auth().currentUser.uid);

      docPath.get().then((doc) => {
        if (doc && doc.exists) {
          this.userInfo = doc.data();
        }
      });
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM