1

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?

2
  • 2
    getSponsor does not return anything. It just executes some async code. Commented Jul 27, 2017 at 18:34
  • Ah, makes sense. So in order to fix it, I need to turn the code inside getSposor into a function and return that function? Sorry, my JS understanding is a little sub-par. Commented Jul 27, 2017 at 18:49

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, I moved it to mounted and declared the data on the Vue instance and it works. Thank you!
Minor nit: the computed property at this point is superfluous. Otherwise, I like it!
@BertEvans You are right, but maybe he wants to do a transformation on the value
The sponsor computed will actually cause a "Maximum call stack size exceeded" error because it's returning itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.