Auzy
Auzy

Reputation: 2155

Issue calling Vue Method via Vue Computed

I believe this issue is related to JS in general as opposed to VueJS. But I have the following Vue Method that returns a Firebase Call and returns the object asked for. This is working:

methods: {
  getSponsor (key) {
    db.ref('businesses').child(key).on('value', snap => {
      console.log(snap.val())
      return snap.val()
    })
  }
}

[Object]

Now, when I call this method from a computed property, it results in undefined:

computed: {
  sponsor () {
    console.log(this.getSponsor(key))
    return(this.getSponsor(key))
  }
}

Undefined

Why is this? Is it because of how I return my method?

Upvotes: 1

Views: 3995

Answers (1)

Nati V
Nati V

Reputation: 702

When you call to async action you getting out from the function context, meaning you can't return a value from the callback function that will be returned in the main function.

The solution for your problem is to set from the callback function a property in the data (declare it first) and then in your computed property get the value of that property.

 computed: {
    sponsor () {
        return(this.sponsor)
    }
 }
 methods: {
  getSponsor (key) {
    let self = this;
    db.ref('businesses').child(key).on('value', snap => {
      console.log(snap.val())
      self.sponsor =  snap.val()
    })
  }
 }

If you will call to the getSonsor inside your computed property it will runs twice, once in the initilaztion proccess and once when the sponsor property will change.

Because you only need to run it once I guess or on event you can do it on beforCreate/mounted etc.. depend on your needs

Upvotes: 1

Related Questions