"Despite using vue.js mounted function, my data remains unchanged after making asynchronous calls to

After trying to find a solution on the internet for my specific case, I decided to call data from firebase using this line of code:

this.$store.dispatch('getConsumptionFromFirebase')

However, I encountered an issue where the mounted() function in my Doughnut.vue file is being called before I fetch data from firebase. As a result, when I navigate to another component and return, the data is rendered because it was previously loaded. How can I resolve this problem and ensure that the data is rendered instantly? Here is my code:

Code snippet from mainComponent.vue file:

<Doughnut class="chartSize" :labels="labelsDoughnut" :data="dataDoughnut" :colors="backgroundColorDoughnut"></Doughnut>

<script>
  import { mapGetters } from 'vuex'
  import Doughnut from '@/components/Graphs/Doughnuts'
  
  export default {
    components: {
      Doughnut
    },
    data () {
      return {
        labelsDoughnut: [ 'Air Conditioning & Heating', 'Cleaning Appliances' ],
        backgroundColorDoughnut: [ '#41B883', '#E46651' ]
      }
    },
    computed: {
      ...mapGetters({
        airConditioningHeatingMonthlyConsumption: 'airConditioningHeatingMonthlyConsumption',
        cleaningAppliancesMonthlyConsumption: 'cleaningAppliancesMonthlyConsumption'
      }),
      dataDoughnut: function () {
        return [ this.airConditioningHeatingMonthlyConsumption, this.cleaningAppliancesMonthlyConsumption ]
      }
    },
    created () {
      this.$store.dispatch('getConsumptionFromFirebase')
    }
  }
</script>

Code snippet from Doughnut.vue file:

<script>
  import { Doughnut } from 'vue-chartjs'
  
  export default {
    props: ['labels', 'data', 'colors'],
    extends: Doughnut,
    
    data () {
      return {
        chartOptions: {
          legend: {
            position: 'top'
          }
        },
        dataCollection: {
          labels: this.labels,
          datasets: [ { data: this.data, backgroundColor: this.colors } ]
        } 
      }
    }, 
    
    mounted () {
      this.renderChart(this.dataCollection, this.chartOptions)
    }
  } 
</script>

Answer №1

It appears that you are manually rendering your component by invoking

this.renderChart(this.dataCollection, this.chartOptions)

Perhaps utilizing computed properties instead of data and implementing watchers could be beneficial:

<script>
  import { Doughnut } from 'vue-chartjs'
  export default {
    props: ['labels', 'data', 'colors'],
    extends: Doughnut,
    computed: {
        chartOptions () {
          return {
            legend: {
              position: 'top'
            }
          }
        },
        dataCollection () {
          return {
            labels: this.labels,
            datasets: [ { data: this.data, backgroundColor: this.colors } ]
          } 
        }
    },
    mounted () {
      this.renderChart(this.dataCollection, this.chartOptions)
    },
    watch: {
      chartOptions: function () {
        this.renderChart(this.dataCollection, this.chartOptions)
      },
      dataCollection: function () {
        this.renderChart(this.dataCollection, this.chartOptions)
      }
    }
  } 
</script>

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

A step-by-step guide on converting a URL image to base64 in Vue

I'm currently working on converting an image URL from Facebook login and I want to accomplish this task using Vue. getDataUri(url, callback){ let img = new Image() img.onload = () => { let canvasElm = documen ...

The authentication protocol, Next Auth, consistently provides a 200 status response for the signIn function

I ran into a challenge while building my custom login page using Next Auth. The issue arises when I try to handle incorrect login data. If the login credentials are correct, I am able to successfully send JWT and redirect to /dashboard. However, when the l ...

Creating a sophisticated structure in real-time

Each user's permissions will vary based on their roles. My goal is to create an object structure like this: let permissions = { 'state': { 'tool': ['subTool1', 'subTool2'] } } Here is an example ...

The value selected is not being shown using uib-typeahead in the user interface

Within my AngularJS application, I am utilizing uib-typeahead to provide auto-suggestions in a text box. As I start typing, I can see the suggestions appearing. However, when I select one of the options, it does not display in the text field (ng-model). I ...

Convert string IDs from a JSON object to numerical IDs in JavaScript

My goal is to convert the IDs in a JSON object received from PHP into numeric keys using JavaScript. The initial structure of my JSON object looks like this: let foo = {"66":"test","65":"footest"}; What I aim for is to transform it into this format: let f ...

Using JQuery to send a POST request to a NODEJS server running on Express

UPDATE: Link to project on Github: https://github.com/jackphumphrey/medisearch Being new to NODEjs, I apologize in advance if this question seems trivial I am trying to issue a POST request using JQuery ($.post) from: /public/javascripts/user.js The use ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...

The npm install command failed due to a lack of suitable versions for pinkie-promise

I am currently attempting to perform a straightforward "npm install" from one of the repositories mentioned in a tutorial provided here Below is the content of the package.json: { "name": "react-playlist", "version": "1.0.0", "description": "A basi ...

Displaying sorted objects from Angular serviceIn Angular 8, let's retrieve an object

In my Angular8 application, I am running a query that fetches a data object. My goal is to sort this data object based on the order value and then display each product item on the browser. For example, here is an example of how the output should look like ...

How can I resolve the issue of a duplicate entry with the key 'PRIMARY' having value '1'?

Using knex for the backend and Vue.js for the frontend. Everything is working fine except for the post function, which returns a 'Duplicate entry' error when submitting the form. How can this be fixed? exports.up = function(knex) { return knex ...

Capture the text content of a TextView in React Native and then transfer it to the clipboard

I'm attempting to implement functionality where, upon clicking an icon, the value inside a textview is copied. Here is my current progress: render() { return ( <View style={{marginTop: 50, marginLeft: 50}}> <View& ...

Angular click event not functioning properly on elements loaded via http request

Check out my CodePen link: http://codepen.io/gauravcoder/pen/vLWEjJ?editors=101 I'm just getting started with Angular JS. I have some items that trigger an alert when clicked, it works fine for items that are not loaded via an HTTP request. However, ...

Calling Ajax to Flask for fetching MySQL query results

My goal is to populate a drop-down list in my HTML using AJAX by calling my flask app app.py from app.js. I am attempting to load the data when the page initially loads and triggering the AJAX within $(document).ready as shown below: Here is the content o ...

Network displays response body but not console output

After sending a request to a link, I noticed that the response logged in the console (console.log(res) and console.log(res.body)) displayed a ReadableStream with no content inside. The value of bodyUsed is also set to false, which is puzzling me at the mo ...

What steps can I take to streamline this code and enhance its elegance in writing?

Working on some practice problems involving higher-order functions, I managed to solve this particular problem. However, the code I used feels somewhat messy and not as elegant as it could be. Is there a better way to combine map and reduce for a cleaner s ...

Boost the elements' worth within an array

Assume I am working with an array shown below... let myArr = [0,0,2,0,0]; I am aiming to generate a ripple effect where the modified array becomes [0,1,2,1,0] ...

Set a generic function type to a variable

Currently, I am facing an issue where I have a declared function type with generics that I want to assign to a named arrow function. Below is an example of the code: import { AutocompleteProps } from '@material-ui/lab/Autocomplete'; const itemTo ...

Displaying an image in VueJS using a custom function

I'm currently learning VueJS and struggling with a particular issue. display.vue <template> <img :src="getLogo(logo)" /> </template> <script> export default { methods: { getLogo(logo){ return '../asse ...

Dynamically populate a list before submitting the form using asp .NET MVC

Are you looking to create a form where users can input multiple owners' details before submitting? Imagine this: the user fills in one owner's information, clicks on "add another owner," and repeats the process until all owners are added. Only th ...

ReactJS: Understanding the Interconnectedness of Components

In my application, I have two main components: Table (which is a child of Tables) and Connection (which is a child of Connections). Both Tables and Connections are children of the App component. The issue I am facing is that the Table component needs to be ...