Louis Stephens
Louis Stephens

Reputation: 105

Populating a field with firestore data in vue

I am building a simple vue app where I am registering/logging in users where they are redirected to their own "special" page. I have created a collection (using firestore) called profiles where I am successfully saving all the custom data in a structure like:

profiles =>
    ABCDEF1234 (user.uid) =>
        role =>
            customrole: true
        bio: "Morbi leo risus, porta ac consectetur ac, vestibulum at eros."
        etc: "etc"    
        etc: "etc"    
        etc: "etc"

I have an input in my view where I was trying to pass the bio to, so they can edit their bio, but for the life of me I can not get it to fetch the data.

  <input
    type="text"
    name="bio"
    placeholder="bio"
    v-model="info.bio"
  />

I could be completely off in how you are supposed to do this, but this is what I currently have. In my data() I currently have:

    data() {
        return {
            user: null,

            info: {
                bio:null,
            }
        };
    },

I then have in created() (might not be the correct spot for this)

const test = firebase.auth().currentUser
  return {
   info: firebase.firestore().collection('profiles').doc(test.uid)
  }

I guess I have wrongly assumed that this would "associate" the collection profiles with the current logged in user to info, and then would be used in my data above for me to call like {{info.bio}}. I am still very new to vue, and any helpful guidance or constructive criticism would be hugely appreciated.

Upvotes: 0

Views: 409

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

Since you didn't show a lot of details about your overall Vue.js app architecture, I make the assumption that firebase.auth().currentUser returns the current user (i.e. the user is logged in).

Therefore, the following should do the trick:

  mounted: function() {
    const user = firebase.auth().currentUser;
    if (user) {
      firebase
        .firestore()
        .collection("profiles")
        .doc(user.uid)
        .get()
        .then(doc => {
          if (doc.exists) {
            this.info.bio = doc.data().bio;
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function(error) {
          console.log("Error getting document:", error);
        });
    }
  }

Fetching a document from Firestore is an asynchronous operation that returns a Promise. You therefore need to use the then() method, as explained in the Firestore documentation, in order to wait for the Promise to resolve before being able to assign the value of bio to your corresponding Vue.js data property.

Upvotes: 1

Related Questions