VueJS: Show content of PromiseResult that is returned from computed property

529 Views Asked by At

I have computed property as shown below which returns res, where res is a Promise object. The reason I am not able to have this script inside created() or mounted() hook is because this.selectedObject is null when I do so.

I am happy with res, however, the problem comes when I need to render PromiseResult in html: <div>{{ currentDepStatus }}</div>. This shows [Promise object] instead of showing content of PromiseResult. Any help would be highly appreciated.

  computed: {
    currentDepStatus() {
      let res = '';
      if (!this.selectedObject) return [];
      const deps = this.depCategory(this.selectedObject.id);
      if (deps.length > 0) {
        res = sendDepStatus(deps);
      }
      return res;
    },
1

There are 1 best solutions below

0
On BEST ANSWER

This is an anti-pattern for how you want to do this. computed properties need to simple getters for nested reactive values. Any external operation should be inside methods

After seeing your problem, here is how I will do it.

data() {
  currentDepStatus: []
}
watch: {
 async selectedObject() {
   if (this.selectedObject) {
      const deps = this.depCategory(this.selectedObject.id);
      if (deps.length > 0) {
        this.currentDepStatus = await sendDepStatus(deps);
      }
    }
  }
}

<div>{{ currentDepStatus }}</div>