Utilizing Vuex to manipulate data with Vue Google Chart

I am looking to retrieve data from the store, perform some operations on it, and then pass it to the vue-google-chart component in the template. Here is my current implementation:

export default {
  name: "Chart1",
  components: {
    GChart, // vue google chart component
  },
  data() {
    return {
      data: null,
      totalGeneral: 0,
      totalHomme: 0,
      totalFemme: 0,
      dataHomme: null,
      dataFemme: null,
      filieres: null,
      chartData: [],
      chartOptions: {
        chart: {
          title: "STUDENTS BY ROUTE INITIAL TRAINING",
        },
        is3D: true,
      },
    };
  },
  created() {
    this.$store.dispatch("setFiData"); // calls the API
  },
mounted() {
    this.getData();
  },

methods: {
    getData() {
      this.data = this.$store.getters.fiData;
      this.chartData = [];
      this.dataFemme = [];
      this.dataHomme = [];
      this.filieres = [];
      if (this.data.length) {
        for (let i = 0; i < this.data.length; i++) {
          this.chartData.push([this.data[i].filiere, this.data[i].total]);
          this.dataHomme.push(this.data[i].homme);
          this.dataFemme.push(this.data[i].femme);
          this.filieres.push(this.data[i].filiere);
          this.totalHomme += this.data[i].homme;
          this.totalFemme += this.data[i].femme;
        }
        this.totalGeneral = this.totalHomme + this.totalFemme;
      } else {
        console.log("NO DATA");
      }
    },
},
},

Every time I run this code, I consistently get the message "NO DATA" in the console. I'm unsure why this is happening. Is there a more effective way to resolve this issue?

Answer №1

Ensure that your code for executing this.$store.dispatch("setFiData") is functioning correctly and properly updating the fiData in your store.

Since it appears that this API call is asynchronous, I recommend following this approach. It would also be helpful if you could share the Vuex store related to this issue.

export default {
  name: "Chart1",
  components: {
    GChart, // Vue Google Chart component
  },
  data() {
    return {
      data: null,
      totalGeneral: 0,
      totalHomme: 0,
      totalFemme: 0,
      dataHomme: null,
      dataFemme: null,
      filieres: null,
      chartData: [],
      chartOptions: {
        chart: {
          title: "STUDENTS BY ROUTE INITIAL TRAINING",
        },
        is3D: true,
      },
    };
  },
  
 mounted() {
   this.$store.dispatch("setFiData") // Call the API here
   .then(() => {
     // Run getData() once the API request completes
      this.getData();
   })
  },

methods: {
    getData() {
      this.data = this.$store.getters.fiData;
      this.chartData = [];
      this.dataFemme = [];
      this.dataHomme = [];
      this.filieres = [];
      if (this.data.length) {
        for (let i = 0; i < this.data.length; i++) {
          this.chartData.push([this.data[i].filiere, this.data[i].total]);
          this.dataHomme.push(this.data[i].homme);
          this.dataFemme.push(this.data[i].femme);
          this.filieres.push(this.data[i].filiere);
          this.totalHomme += this.data[i].homme;
          this.totalFemme += this.data[i].femme;
        }
        this.totalGeneral = this.totalHomme + this.totalFemme;
      } else {
        console.log("NO DATA");
      }
    },
},
},

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

Sharing data between two React components

In my React application, I have implemented two components. One of them is the header component which includes a slider. I am now looking for a way to trigger an event in the second component whenever the slider value changes. Initially, I attempted usin ...

Encountered unexpected character error while parsing JSON data

I am encountering the following error message: JSON.parse: unexpected character when I execute this code in firebug: JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":fals ...

Leveraging a Service Property Initialized by Callback Function Across Different Components in Angular

When I try to access the myData property of a DataService in my DataComponent, it is undefined due to waiting for callback. How can I properly utilize and access this data? export class DataService { public myData; constructor(private http: HttpClien ...

After successfully authenticating, you may introduce a new React component

Currently, I am working on a page that will only display information once a user has logged into their account. I have successfully implemented an authentication system using NodeJS, and now my goal is to restrict access to specific components or pages bas ...

Sequence of text array contains a gap

I'm struggling with a simple array text sequence where A, B, and C need to show for 2500ms each before cycling back through. Currently, there is a blank frame displayed for 2500ms that I can't seem to get rid of. Does anyone have a solution to ...

Iterate over a collection of HTML elements to assign a specific class to one element and a different class to the remaining elements

Forgive me if this is a silly question, but I have a function named selectFace(face); The idea is that when an item is clicked, it should add one class to that item and another class to all the other items. This is what I currently have: HTML <div c ...

What could be causing my bootstrap-switch to malfunction?

Here is the snippet of code I am working with: jQuery.each($('.onoffswitch-checkbox'), function(i, slotData) { console.log($(slotData).bootstrapSwitch('state')) }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1 ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

Choosing our hourly availability?

I came across a reference to a similar question on Stack Overflow. Although I attempted to find a solution, I have not been successful so far. <div class="form-group"> <label>Working Hours :</label> <div v-for="value in day" c ...

How to retrieve query parameters from the base of a URL in Express.js (A different approach from using req.params)

Recently, I created an API and set up the routing in the following manner: Starting with the main routes file: // Sub-route included app.use('/api/test/:test', require('./api/test')); // Without sub-route app.use('/api/t ...

What is the significance of the -infinity value in the JavaScript console?

Recently, while learning JavaScript ES6, I came across a strange result of -infinity on my console when running the following code: let numeros = [1, 5, 10, 20, 100, 234]; let max = Math.max.apply(numeros); console.log(max); What does this ...

What is the best way to trigger a method to rerun when you revisit a screen in react-native?

After writing a method, I attempted to call it in the componentDidMount(), componentWillMount(), and render() methods in React-Native. However, the method does not run again. My goal is to have this method executed every time the screen is visited. ...

Exploring the functionality of test code within an rxjs subscription by utilizing the powerful technique of jasmine

My goal is to test the code within an observable subscription: function bar(someStream$: Observable<number>) { someStream$.pipe( map((x) => x + 3), ).subscribe((result) => { SomeService.someMethod(result) }) } I want to ensure t ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

Empty placeholder image appearing at the beginning of JavaScript slideshow in Ruby on Rails

As a newcomer, I ask for your understanding if I lack knowledge in some areas. I have been working on a project and using the cycle2 plugin successfully to create a slideshow on my index page with images pulled from the internet. Now, I am trying to impl ...

Transmitting real-time updates from a lengthy asynchronous task in a Node Express Server to a React client

I am looking for a way to send progress data from a long-running async function on a node express server to a client when the client requests and waits for completion. const express = require('express'); const app = express(); const port = proces ...

Utilizing Bootstrap modal to insert data into phpMyAdmin database - a comprehensive guide

I'm attempting to insert data into my localhost database using a Bootstrap modal in conjunction with Laravel 5.2. Here is the PHP function I am using: public function addReport(Request $request) { $postreport = new PostReport(); $postreport- ...

Unable to locate the control specified by the path: 'files -> 0 -> postId'

I am in the process of creating a dynamic form with formArray and running into an issue. When I click on the AddItem button, it should create an input field for uploading files. Here is the HTML code snippet I am using: <div class="row m-auto col-md-1 ...

Using Kendo's Angular Grid to link data sources

I'm currently facing a minor issue with the Kendo Grid for Angular. My attempt to bind data after fetching is resulting in the following error: ERROR TypeError: Cannot read properties of undefined (reading 'api') This indicates that this. ...

Ways to set the minimum width of a div depending on its contents

As I work on my website, I encountered an issue with a div containing a table. The div expands to full width, but when I resize the screen, it shrinks causing the content to overlap. I am looking for a solution where the minimum width of the div adjusts b ...