When using promises in Vue, you can expect to receive an observer object

In my Vue.js project, I am trying to trigger a Vuex action in the created() lifecycle hook and then proceed to call an asynchronous method to fetch more data from the server upon receiving the initial data. The goal is to utilize this data in a component. However, I encountered an issue with the Observer returned from the Promise. I attempted to switch the data to a computed property without success. I also tried using await, but it didn't resolve the problem either. Interestingly, another computed property named item functions correctly. I understand that the Observer plays a crucial role in Vue's reactivity system, but I'm unsure how to troubleshoot this.

<SeriesBarChart v-if="!inProgress" :series="series" /> // initial implementation
<SeriesBarChart v-if="!inProgress" :series="groups" /> // attempt using a computed property

data: () => ({
  series: [{}, {}],
  inProgress: true,
}),
created() {
  this.$store.dispatch('GET_POLL', { slug: this.slug }).then(() => {
    this.runQueries(this.item._id, ['vehicles=car&vehicles=bike', 'region=PRG']); // despite attempting await here, unsuccessful
  });
},
computed: {
  item() {
    return this.$store.getters.POLL;
  },
  groups() {
    return this.series;
  },
},
methods: {
  async runQueries(id, queries) {
      this.inProgress = true;
      const promises = [];
      for (let i = 0; i < queries.length; i += 1) {
        promises.push(this.$store.dispatch('GET_POLL_VOTES', { id, query: queries[i] }));
      }
      Promise.all(promises).then((values) => {
        for (let i = 0; i < values.length; i += 1) {
          this.series[i] = values[i].data.data;
        }
      });
      this.inProgress = false;
    }

Answer №1

Since Yom has not shared an answer and even removed his helpful comment, I will provide my own answer for those who may come across this in the future. The Observer object was introduced by Vue because there was a mistake of having the statement this.inProgress = false; placed outside of the then block. Below is the corrected code that functions as intended:

async runQueries(id, queries) {
  this.inProgress = true;
  const promises = [];
  for (let i = 0; i < queries.length; i += 1) {
    promises.push(this.$store.dispatch('GET_POLL_VOTES', { id, query: queries[i] }));
  }
  Promise.all(promises).then((values) => {
    for (let i = 0; i < values.length; i += 1) {
      this.series[i] = values[i].data.data;
    }
    this.inProgress = false;
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the advantages of compiling our CSS and JS files in Laravel? How does it benefit us?

Just starting out with Vue and came across a video where they were compiling their assets. Got me thinking, why do we need to compile our assets? Can we use Vue and Vue-router in Laravel without asset compilation? If so, how? ...

Performing a JSON POST Request: Steps for sending a POST request with JSON data format

I need to send the following data: { "contactsync": { "rev":4, "contacts":[ { "fields": [ { "value": { ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...

Unable to retrieve the value stored in the global variable

I recently updated my code to use global variables for two select elements in order to simplify things. Previously, I had separate variables for values and innerHTML which felt redundant. Now, with global variables like user and group initialized at docum ...

Creating dynamic elements in JavaScript and assigning them unique IDs

Hi there, I'm currently working on a project that requires generating dynamic divs with a textbox and delete button inside each one. The challenge I'm facing is figuring out how to assign a unique ID to each textbox element so that I can properly ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

When multiple checkboxes are selected by the user, corresponding form fields should appear based on the checkboxes. For example, if both flight and hotel checkboxes are checked, then the full name and last name fields should be displayed while other fields ...

Ways to extract the ASP.net variable value and place it inside a JavaScript textbox

Currently, I'm in the process of developing Javascript code for an ASP.net page. Within my coding framework, the string "foo" is linked to a string variable called myString. In order to transfer the value of myString to a JavaScript variable, I incl ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Angular UI Accordion with full-size clickable panels available for interaction (?)

I'm facing a simple issue and I can't figure out why I'm not getting the desired behavior. I am currently utilizing the Angular UI Bootstrap accordion, however, in the provided example, the only way to open the accordion is by clicking on th ...

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Using React.js with a PHP backend to create an API ecosystem for

Creating an admin panel for a website with CRUD operations has been quite the journey. I began by setting up API endpoints and hosting them on a subdomain. Fetching data from these endpoints was successful for displaying all contacts (GET), individual cont ...

Vue.js parent component not receiving data emitted by child component

Below you will find the child and parent components. I am struggling to pass data from the child component to the parent component. Can you help me pinpoint where the issue may be? Child Component <template> <div> <v-btn class="r ...

Is there a way for me to make the login button redirect to the Dashboard?

I'm currently working on a piece of code where I need to implement some form of validation when the user clicks on the sign-in button. Specifically, I want to ensure that both the username and password fields are not left empty. If this condition is m ...

What is the best approach for organizing JavaScript/CoffeeScript in a Rails 5 project for optimal efficiency?

I am currently working on a web application with Rails 5.0.2 and I have a set of JS files for the project: https://i.stack.imgur.com/WYB23.png Each of my own JS files follows a similar pattern, like this: $(function () { var init = function () { ...

Saving Files in Your React Web Application: Tips and Tricks

Currently, I am working on a React web application that requires the temporary storage of Torrent pieces for streaming purposes using a web player. Any recommendations on how to properly store this data temporarily in order to facilitate the streaming pro ...

Function in head not triggering on OnMouseOver event

My goal is to have specific text display on my page when a user hovers over an image, with the text changing for each image. Below is the code snippet for the header section: <head> <title>Indian Spices Page</title> <link rel="s ...

Using the JavaScript JSX syntax, apply the map function to the result of a

My aim is to create a structure resembling the following: <td> {phones.map((phone, j) => <p>{this.renderPhone(phone)}</p> )} </td> However, there may be instances where the phones array is not defined. Is it feas ...

Is there a way to adjust the brightness of specific sections within an image using html, css, and js?

I am working on a project where I have an image with tags underneath that correspond to different parts of the image. For example, if the image is of a dog, one of the tags could be 'nose', indicating the portion of the image around the dog' ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...