Return boolean based of values of an object

I’ve created a computed method to test if any axios calls are currently loading, but my computed method doesn’t update sometimes.

<template>
  <div v-if="areResourcesLoading">Loading...</div>
</template>

data () {
  return {
    resourceLoadingStatuses: {
      getStatusByClient: false,
      getSelectedOrders: false,
      getOrders: false,
      searchProducts: false
    },
  }
},

computed: {
  areResourcesLoading() {
    return Object.values(this.resourceLoadingStatuses).includes(true);
}

methods: {
  axiosCall() {
    this.resourceLoadingStatuses.getSelectedOrdersSearch = true;

    axios.get("/the/api/call")
        .then(response => { // Do stuff })
        .catch(error => { // Handle errors })
        .finally(() => {
          this.resourceLoadingStatuses.getSelectedOrdersSearch = false;
        });
  }
}

I’ll inspect the component using Vue devtools and see that all the resourceLoadingStatuses values are false, but areResourcesLoading still evaluates to true. I can toggle one of the resourceLoadingStatuses values from false to true and back to false using Vue devtools, and the areResourcesLoading computed method will then return false.

Any idea what I’m doing wrong? I’m also open to a better solution.

Hi. You could have a counter which is increased when you start the loading and decreased then loading finished or fails. Then you only need to keep track of one value.

I don’t know why it doesn’t work. You could also just compute

  getStatusByClient ||
  getSelectedOrders ||
  getOrders ||
  searchProducts

I converted my areResourcesLoading method to:

return this.resourceLoadingStatuses.getStatusByClient ||
        this.resourceLoadingStatuses.getSelectedOrders ||
        this.resourceLoadingStatuses.getOrders ||
        this.resourceLoadingStatuses.searchProduct;

This works fine, but I’d love to understand why return Object.values doesn’t work though as that seems like a more DRY solution.

There is no getSelectedOrdersSearch in your data

My code has evolved since I’ve posted this, but I went ahead and reverted back to return Object.values(this.resourceLoadingStatuses).includes(true); and it seems to be working. I must have type-oed.

Thanks @johandalabacka & @valq7711

1 Like