How to access firebase prop's values inside a method (Vuefire)?

258 Views Asked by At

In my component, I am doing :

firebase() {
  const userId = firebase.auth().currentUser.uid
  return {
    race: userRef.child(userId).child('races').child(this.raceKey)
  }
},
mounted () {
  console.log(this.$firebaseRefs.race.name)
}

I can access the race property's values inside my component's template, but I cannot figure out how to access them inside a created hook or a method. The value is always undefined. How can I do this?

The structure for the race is:

race: {
 name: "the name",
 .....
}
2

There are 2 best solutions below

0
On BEST ANSWER

Solved it using the readyCallBack function. The problem was mounted triggered before the firebase reference had actually loaded. Thank you Renaud Tarnec for the help.

firebase() {
  return {
    race: {
      source: userRef.child(firebase.auth().currentUser.uid).child('races').child("-LMgzo_50TzlfJwCblDS"),
      asObject: true,
      cancelCallback: function () {},
      readyCallback: function() {
        console.log("Firebase race was loaded")
        this.renderMap()
      }
    }
  }
}
0
On

This is because queries to Firebase Real Time Database are asynchronous, and therefore there is no guarantee that you get the result of your query in a lifecycle hook like mounted. In other words, the Firebase binding of your race object does not finish before the instance is mounted.

See the following posts for more detail and possible workaround with readyCallback:

https://github.com/vuejs/vuefire/issues/70 and https://github.com/vuejs/vuefire/issues/69