0

I'm trying to set a variable with the information that i got from a get() function on firebase, but i can't.

 export default {
    name: "customer-navigation",
mixins: [navigationMixin],
components:{AppSnackBar, authModule,AuthForm},

data () {
      return {
    drawer: false,

    items: [
      { title: this.$t('navigation.home'), icon: 'home', to: '/' },
      { title: this.$t('navigation.shop'), icon: 'shopping_basket', to: 
 '/shop' },
      { title: this.$t('navigation.cart'), icon: 'shopping_cart', to: 
 '/cart' },
      { title: this.$t('navigation.orders'), icon: 'view_headline', to: 
 '/orders' },
    ],
    img_url: "" ,
    nombreFire: "",
  }
},
methods: {
  getInfo(){      

 db.collection('users').doc(authModule.state.user.uid).get().then(function(doc) {        
      this.img_url = doc.data().img_url
    })     




  }
}


}

Uncaught (in promise) TypeError: Cannot set property 'img_url' of undefined at eval, this i the error that i get

1 Answers1

2

Your error states that it cannot set the property img_url of undefined. Looking at your code, you're setting the property img_url for the object this.

this is undefined because you're in a callback function. What you can do is modify your getInfo method as follows:


getInfo() {
  const vm = this; //this is the vue module.
  db.collection('users').doc(authModule.state.user.uid).get().then(doc => {
  vm.img_url = doc.data().img_url; //set the passed-in 'this'
});

This question can provide more insight on scoping 'this' in callbacks

Tanner
  • 2,232
  • 13
  • 22
  • 2
    Just note that if you are using arrow functions you don't need to do `const vm = this;` and you can use `this`, because, in an arrow function, `this` does not refer to the owner of the function. Actually, the SO answers you link to also mentions that. – Renaud Tarnec Oct 02 '19 at 16:39