Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label, indicatorValue, etc).

The issue is that the component does not re-render when the data within the Promise changes (e.g. when applying application filters or interacting with charts). The component's data only updates when switching routes or reloading the page.

What Vue solution can be used to monitor changes coming from the Promise?

data() {
    return {
        label: null,
        indicatorState: null,
        indicatorValue: null,
    }
},
computed: {
  isAppReady() {
    return this.$store.getters.isAppReady;
  },
},
mounted() {
  this.$store.watch(() => this.isAppReady, (status) => {
    if (status) { // if STATUS === true
      this.getData();
    }
  });

  if (this.isAppReady) {
    this.getData();
  }
},
methods: {
  getData() {
    return this.appMethods // global object gathering specific methods like .getObject, .getField etc.
      .getObject(null, this.visualID)
      .then(visualData => visualData.layout.cube.dataPages[0].matrix[0])
      .then((transformedData) => {
        this.label = transformedData[0].qText;
        this.indicatorValue = transformedData[1].qText;
        this.indicatorState = Number(transformedData[1].qNum) > 0;
      });
  },
}, 

Answer №1

When utilizing Vuex, it is recommended to separate data fetching logic from the component,

  • Transfer the getData() method to a service
  • Invoke it in the click handler of any component where a refresh is needed
  • Add new data to the store
  • Retrieve the properties from the store

Service code

getData() {
  return this.appMethods 
    .getObject(null, this.visualID)
    .then(visualData => visualData.layout.cube.dataPages[0].matrix[0])
    .then((transformedData) => {
      this.$store.commit('SET_MY_DATA', transformedData);
    });
}

Access via computed properties in the component

computed: {
  label() {
    return this.$store.getters.label
  } 
  indicatorState() {
    return this.$store.getters.indicatorState
  } 
  indicatorValue() {
    return this.$store.getters.indicatorValue
  } 
},

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

An error was encountered in the index.js file within the app directory when running the webpack

Recently, I was told to learn react.js even though my knowledge of javascript is limited. Nevertheless, I decided to dive in and start with a simple "Hello World" project. Initially, when I used the index.js file below and ran webpack -p, everything worke ...

Is there a way to hide a paragraph or div using javascript?

I am experimenting with using buttons to hide paragraphs using javascript, but even when I set them as "hidden", there is still excess blank space left behind. Is there a way I can eliminate that extra space? Below is the javascript code: function backgro ...

Having trouble getting jQuery autocomplete to recognize the JavaScript data file

Struggling to use a JQuery UI widget to call in a JS file containing string data. I keep getting 'no results found' with no console errors. It seems like I'm not referencing the file correctly, as my knowledge of jquery/js is limited. Any gu ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Ways to utilize a singular pathway in various situations?

In my Nuxt project, I have implemented an admin dashboard with a unique layout (sidebar) using <NuxtChild> to render child routes: Admin.vue <NuxtChild :key="$route.path" /> Simplified Routes: { path: "/admin", ...

I am unable to eliminate the parentheses from the URL

I am in need of creating a function that can extract the content inside "()"" from a URL: Despite my efforts, the function I attempted to use did not provide the desired result. Instead of removing the "()" as intended, it encoded the URL into this format ...

Utilizing AngularJS to Extract JSON Data from Gzipped Files Stored Locally via Ajax

Currently, I am attempting to retrieve and read a JSON file that is stored in data.gz using AngularJS's $http service. However, when I make the request, all I get back are strange symbols and characters as the response. My application is being run loc ...

Implementing Bootstrap 4 validation within a modal using JSON data

I've been struggling to validate the TextBoxFor before submitting the form. Despite trying various methods, I haven't managed to make it function properly. Modal: <div class="modal fade" id="MyModal_C"> <div class="modal-dialog" st ...

Utilizing Cordova for Windows 8.1 in Visual Studio 2015 for external image retrieval and insertion into img tag

I am encountering an issue with displaying external images in a Cordova app. While the DOM is functioning correctly, the images are failing to load. I am specifically trying to resolve this for Windows 8.1 only. In my Cordova project for JavaScript, I have ...

Javascript encounters an unforeseen < token

I encountered an unexpected token < error in my JavaScript file. Despite checking the code using JSHint, I couldn't find any issues that could resolve the problem. I attempted to place the JavaScript code in a separate file and also tried embeddin ...

Revamp MUI class names with React Material UI's innovative randomization and elimination

Can names be randomized or Mui-classNames removed? https://i.stack.imgur.com/J6A9V.png Similar to the image displayed? (All CSS class names would be jssXXX) Appreciate your assistance. ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

SVG: Altering the dy attribute has no impact on the overall height of the bounding rectangle for the parent text

We are striving to align a group of tspan elements both vertically and horizontally. However, the parent container is not taking into consideration dy values. This lack of consideration is leading to alignment issues. If you adjust the dy values in this ...

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

JavaScript: Working with Nested Callbacks and Retrieving MySQL Data

As I dive into the world of JavaScript server-side code, I find myself grappling with a common issue that many programmers face. In my previous experience with MySQL select queries in PHP, I would simply grab a result and loop through each row, performing ...

What is the best way to pass an array to a child component in React?

I am having an issue where only the first element of inputArrival and inputBurst is being sent to the child component Barchart.js, instead of all elements. My goal is for the data to be instantly reflected as it is entered into Entrytable.js. EntryTable.js ...