Beat Scherrer
Beat Scherrer

Reputation: 307

Vue and firestore data binding

I want to retrieve data from firestore and bind them to the vue data.

I retrieve the firestore data in the following manner in the created lifecycle hook:

  created(){

console.log(firebase.auth().currentUser);
const docRef = firebase.firestore().collection("users").doc("VezLOaumLCza8jih8Ylk");
docRef.get().then(
  function(doc){
    if(doc.exists){
      console.log(`Document data: ${doc.data()}`);
      this.user = doc.data();
    } else {
      console.log(`Doc data is undefined`);
    }
  }).catch(function(err){
    console.log(`Oops: ${err.message}`);
  });
}

The issue is that this does not refer to the vue instance, in fact this is undefined at the point where I'm trying to set the user variable. How can I bind the user data to the vue data? It seems I'm missing something and I can't figure out what might be the issue.

The ultimate goal is to have a form which allows the user to modify his/her data.

(printing out the doc.data() gives the expected results)

Upvotes: 1

Views: 783

Answers (1)

Gabriel Garrett
Gabriel Garrett

Reputation: 2127

The then callback is a separate function, therefore when this is accessed inside of that function, it is referencing the then callback. You need to create a reference to the Vue VM prior to the then callback.

Try this:

created(){

console.log(firebase.auth().currentUser);
const docRef = firebase.firestore().collection("users").doc("VezLOaumLCza8jih8Ylk");
var vm = this; //creating the reference to the Vue VM.
docRef.get().then(
  function(doc){
    if(doc.exists){
      console.log(`Document data: ${doc.data()}`);
      vm.user = doc.data();
    } else {
      console.log(`Doc data is undefined`);
    }
  }).catch(function(err){
    console.log(`Oops: ${err.message}`);
  });
}

Upvotes: 1

Related Questions