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

select items using a dropdown menu in an Angular application

Let me describe a scenario where I am facing an issue. I have created an HTML table with certain elements and a drop-down list Click here for image illustration When the user selects in, only records with type in should be displayed Another image refere ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

Encountering a DiscordAPIError[10062] when attempting to retrieve user points from the database due to an unknown interaction

content: "Congratulations, you have been successfully verified!", ephemeral: true, }); } } else if (interaction.customId === "giverole") { const userPoints = await findUser(interaction.member ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Using AngularJS to access form field ids that are generated dynamically

I am dynamically generating form fields using ng-repeat and everything is functioning correctly. However, I now want to incorporate an angular datepicker component that is based on a directive. The issue I am facing is that it only seems to work with stat ...

Issue with monitoring property modifications in Vue.js

Issues with Component Variable and Prop Assignment Trying to assign a local component variable to a prop is causing Vue to throw an alert saying "Invalid watch handler specified by key 'undefined'". It's possible that the issue lies in pass ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line: const firstRef = ref<HTMLElement>(null) <template> <input id="first" ref="firstRef"> <button type="button&q ...

Struggling to retrieve a response from the ListUsers endpoint in OKTA using the okta-sdk-nodejs Client's listUsers function

Code snippet: async fetchUsersByEmail(email) { try { return await Promise.all([ oktaClient.listUsers({ search: email, }), ]).then((response) => { console.log(response); }); } catch (error) { ...

Press anywhere outside the container to conceal it along with the button

Utilizing an Angular directive to hide div elements when the user interacts outside of them has been effective. However, there is a specific issue that arises when clicking outside of a div on a button that toggles the visibility of the div. The 'ang ...

Step-by-step guide to implementing a sticky header while scrolling

How can I implement a fixed header on scroll, like the one seen on this website: www.avauntmagazine.com Here is the HTML for my header: <div class="bloc bgc-wild-blue-yonder l-bloc " id="bloc-1"> <div class="container bloc-sm"> &l ...

Can you explain the role of the next() function in middleware/routes following the app.use(express.static(...)) in Express

When dealing with serving static assets generated from React source code using npm run build, the following method can be used: app.use('/', express.static(path.join(__dirname, 'apps', 'home', 'build'))) To protect ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

Exploring TypeScript and React Hooks for managing state and handling events

What are the different types of React.js's state and events? In the code snippet provided, I am currently using type: any as a workaround, but it feels like a hack. How can I properly define the types for them? When defining my custom hooks: If I u ...

Modify the background color based on the length of the input in Vue

Can you change the background color of the initial input field to green if the value of the Fullname input field is greater than 3 characters? See below for the code: <div id="app"> <input type="text" v-model="fullname" placeholder="Enter Full ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...

React Native vector icons display enigmatic symbols

I recently installed react-native-vector, but I'm seeing strange symbols when using it. Can anyone provide guidance on how to properly utilize this library? Platform: Android import React from 'react'; import {View, Text, StyleSheet} from & ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...