Refresh the Google chart in response to a state change in Vuex

Currently, I am working on a reporting page that will display various graphs. Upon entering the page, an API request is made to retrieve all default information. The plan is to enable users to later select filters based on their inputs.

For instance: initial view shows all results, while applying filters narrows down the results.

To achieve this functionality, I am utilizing vuejs for building components, vuex for storing information, and Google Charts for creating the graphs.

The issue I am facing is that when I apply filters, the graphs do not update even though the state is being updated. I have implemented a watcher to monitor changes in the state, but it only triggers when the component is initially created.

Here's a snippet of my code:

Vuex

import axios from 'axios';

const state = {
    dataChart: {}
}

const mutations = {
    'ADD_DATA_CHART'(state, data) {
        state.dataChart[data.key] = [];

        [].forEach.call(data.states, (s, i) => {
            let obj = {};
            obj.name = s;
            obj.data = [];

            [].forEach.call(data.value, d => {
                obj.data.push([d.name, d[data.keys[i]].toFixed(2)]);
            });
            state.dataChart[data.key].push(obj);
        });
    }
}

const actions = {
    fetchReporting({state, commit}, response) {
        axios.post(response.endpoint, response.formData)
            .then(({data}) => {
                commit('ADD_DATA_CHART', {key: response.chart, value: data, states: response.states, keys: response.keys})
            }).catch(err => {
                console.log(err);
            });
    }
}

const getters = {
     dataChart: state => state.dataChart
}


export default {
    state,
    mutations,
    actions,
    getters
}

Component

<template>
    <div class="box-content-white">
        <div class="title">Chart</div>
        <div id="stackedChart"></div>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex';
    import { mapActions } from 'vuex';

    export default {
        props: {
            endpoint: String,
            chart: String,
            states: Array,
            keys: Array
        },
        data() {
            return {
                 data: []
            }
        },
        methods: {
            // Methods here
        },
        mounted() {
            // Fetch data and mount chart
        },
        computed: {
            ...mapGetters({
                dataChart: 'dataChart'
            })
        },
        watch: {
          // Watcher implementation
        }
    }
</script>

I am currently stuck on this issue. Any suggestions or solutions are greatly appreciated!

Answer №1

If you want to ensure that state.dataChart is reactive, remember to assign it to a new object reference.

Using ES6 syntax:

const mutations = {
    'ADD_DATA_CHART'(state, data) {
        var updatedData = []
        [].forEach.call(data.states, (s, i) => {
            let newObj = {};
            newObj.name = s;
            newObj.data = [];

            [].forEach.call(data.value, d => {
                newObj.data.push([d.name, d[data.keys[i]].toFixed(2)]);
            });
            updatedData.push(newObj);
        });
        state.dataChart = {
          ...state.dataChart,
          [data.key]: updatedData
        }
    }
}

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

Access the serialized form data fields using Express.js

I'm currently facing difficulty in accessing specific fields of my serialized formdata within my express router. Here is the ajax request I am using: var formData = $("#add-fut-account-form").find("select, textarea, input").serialize(); $.ajax({ u ...

Refreshing the page results in a 404 error when utilizing React Router

I am currently facing an issue with my web application setup. Back-End My back-end consists of a Node.js/express server that serves files in response to specific requests made to certain routes. Front-End On the front-end, I have React pages that commu ...

Challenges with fading images using jQuery

I am currently working on animating a 5 image slideshow by creating a fading effect between the images rather than just switching abruptly. Here is my HTML structure: <div id="slides"> <ul class="pics"> <li><img src="imag ...

verifying if checkbox is selected using a while loop in PHP

Help Needed: I am currently trying to loop through some code, but I'm struggling with checking checkboxes using PHP. Could someone please review my code and provide guidance on what needs to be added? Any assistance would be greatly appreciated. Thank ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Restricting slash commands in Discord.js to a specific permission level

I'm currently developing a purge command, and I'm struggling to restrict its usage to users with the MANAGE_MESSAGES permission. Below is the source code for the client.on("ready") section as well as the entire command logic. Any assistance on ...

An error occurs when trying to call a function that is defined within the methods{} block from outside

export default{ name: 'navigation', components:{ menuIcon, }, data() { return { mobile: null, mobileNav: null, windowwidth: null, } }, methods: { checkScreen() { this.windowwidth = window.innerWidth ...

JavaScript Hangman Game Malfunctioning

I am in the process of creating a basic hangman game to be played on a web browser. Whenever the user clicks a button, it triggers a function called pickWord(): <button onclick="pickWord()" id="restart">Choose A Word</button> This functi ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel. This is the code in th ...

Tips for How to Put a Delay on Ajax Requests and Display a Progress Bar During Loading

I am using checkboxes in the sidebar. When a user selects a checkbox from the sidebar, it displays the post normally. Is there a way to add a progress bar to delay the Ajax result? This is my Ajax code: <script> jQuery(document).ready(function($){ ...

Parent component failing to capture events triggered by child component

Check out this demo showcasing what I'm anticipating to work: https://jsfiddle.net/qe766xn0/4/ The issue here is that the child component is triggering an event that the parent component isn't able to catch. Based on insights from this resource ...

There was a parsing error due to an unexpected token, and we were expecting a comma instead

Below is the code snippet written in react js: class Posts extends Component { render() { return ( {console.log('test')} ); } } When I executed this code, an error occurred stating: Parsing error: Unexpected token, expected " ...

Problem with Scroll Listener on Image in Angular 4: Window Scroll Functioning Properly

Hello, I am a newcomer who is currently working on creating a small application that allows users to zoom in on an image using the mouse scroll. <img (window:scroll)="onScroll($event) .....></img> The code above works well, however, it detec ...

`JQuery fadeOut seems to have a limitation where it only applies to the

I have a group of divs, each containing an anchor tag that triggers a JavaScript function (which uses AJAX to delete a row from a table). Here's an example setup: <div id="container"> <div><a id="btn" onclick="deleteRow()">Delet ...

Leveraging the browser's console for transmitting AJAX data

I've created a PHP quiz page that uses AJAX to post answer data when a user clicks on an answer. If the answer is correct, the page then loads the next question using another AJAX function. Here's a snippet of the code: <ul class="choices"> ...

Unable to deploy Firebase functions following the addition of an NPM package

Scenario: I recently tried integrating Taiko into my Firebase web application, similar to Puppeteer. It's worth mentioning that Taiko downloads Chromium for its operations. Challenge: Ever since then, none of my functions are deploying successfully. ...

Explore all potentialities within an array of objects by examining and contrasting their key values

Looking to run a specific math formula with three parameters using an array of objects in JavaScript. The scenario involves sports, where there are three possibilities: Team A (win), Team B (win), or Draw. There are three different bet websites offering o ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...

Tips for preventing automatic zoom on mobile devices

Check out this link for the test: The current layout of the site is exactly how I want it to be presented. However, I am facing an issue where if I set the viewport meta tag to <meta name="viewport" content="width=device-width, initial-scale=1"> i ...