[Vuejs]-Why would a computed property return undefined?

4👍

Your allcases computed property is undefined because the method for that computed property is not returning a value. When you return a value in the done callback, that does not magically also get returned in the scope of your computed property method.

Unless you are expecting to fire an async call each time some dependant vue property changes, I wouldn’t make this code a computed property.

I would make allcases a regular data property initially set to null:

data() {
  return {
    allcases: null,
  }
}

Then, I’d put your async call in a new method (say fetchAllcases). In this method you can directly set the allcases data property to msg.hits.hits in the done callback:

methods: {
  fetchAllcases() {
    let self = this;
    console.log('getting all cases')
    var request = $.ajax({
            (...) <- a working AJAX call here, please see below
        })
        .done(function(msg) {
            console.log('found: ' + JSON.stringify(msg.hits.hits));
            self.allcases = msg.hits.hits;
        })
        .fail(function(jqXHR, msg) {
            console.log('error posting incident: ' + msg);
        });
  }
}

Then, just fire this method once in the component’s mounted lifecycle hook:

mounted() {
  this.fetchAllcases();
}

0👍

As per jQuery docs, calling $.ajax returns jqXHR, and that is what you are saving in your request variable, not msg.hits.hits

to achieve what you are trying to do, consider using vue-async-computed

👤Faris

Leave a comment