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

I encountered an error while using the router: TypeError: Cannot read property 'use' of undefined

Hello everyone, I am new to node.js and seeking help from experts. I am currently working on a code for user synchronization using node.js + AWS Cognito + Facebook Login. I followed an example from this link. Everything was going smoothly until I reached ...

Enhance your website's performance by optimizing Javascript page loading time when using

I've implemented a simple JavaScript function that calculates the loading time of a URL: var beforeLoad = (new Date()).getTime(); $('#myiframe').one('load', function() { var afterLoad = (new Date()).getTime(); var result = ...

Is there a way to update the styling of specific sections of an input field as the user enters text in React?

Just like in most markdown editors, I am looking to enable the ability to modify parts of an input field as the user enters text. For instance: When the user types "_above_", as soon as the second underscore is typed, the text should be styled accordingly ...

In Express.js, the value of req.body.data is not defined

Recently, I've been delving into nodejs and express js. My aim is to send a json object to my nodejs application using postman. Below is the code snippet from my app: var express = require("express"); var bodyParser = require('body-parser') ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

"Generate a series of dropdown menus with choices using either jQuery or AngularJS from a JSON dataset

I'm in need of assistance. I want to generate select dropdowns dynamically based on data retrieved from my REST API, which is in JSON format. How can I dynamically inject these selects into my HTML? Below is an example data structure: JSON data fetch ...

What is the best way to eliminate duplicate members from an array of objects by comparing their property values?

The array appears as follows: let example = [ { Time: new Date(1000), psi:100.0 }, { Time: new Date(1000), psi:200.0 }, { Time: new Date( ...

What is the process for accessing the theme spacing unit in MUI 5?

In previous iterations of MUI, accessing the theme spacing unit was possible through theme.spacing.unit, with a default output of 8. However, this property has been removed in MUI 5. I am having trouble finding documentation on how to access the theme sp ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...

The Bootstrap navigation menu fails to extend the parent div when toggled

When I toggle the button to show the menu on small screens, the menu overflows the parent div with id=contents instead of pushing it down. How can this issue be fixed? Here is the code: <body> <nav id="header" class="navbar navbar-default"& ...

Choose a specific inner div element within another div using jQuery

Trying to target a specific div within another div in my HTML structure. Here's how it looks: <div id="Stage_game_page1"><div id="cube0">[...]</div><div id="cube1">[...]</div></div> I am attempting to select #cube ...

Surprising outcomes when using MongooseJS's findOne() method

Currently utilizing Mongoose as the Object Document Mapper (ODM) alongside NodeJS, but struggling with comprehending how error handling functions. It seems to be working, however the implementation appears incorrect and does not align with the documentatio ...

To access the context menu popup and the first element of a row in a datatable, simply right-click on the row

Currently, I am working on writing code for a datatable where when you right-click a row, two actions should be triggered: a context menu should appear, and I need to retrieve the first cell of that row to pass it to my Ajax function. I have managed to wr ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Configuring Django social authentication with a Vue.js frontend

I've recently teamed up with a frontend developer on a new project where we're attempting to integrate social authentication via Discord, but so far we haven't had much luck. For the backend, I'm using django as a REST API and have ins ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

Error: Trying to access a property that is undefined (specifically referencing 'rendered') has resulted in an uncaught TypeError

As a newcomer to React, I'm attempting to create a headless WordPress application. However, when I fetch a post, I only receive the first value. After fetching the post, I save it in the state: componentDidMount() { this.setState({ lo ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...