Utilizing dynamic data in Vue-chartjs through Pinia stores

I am currently exploring how to integrate a Pinia store data with vue-chartjs in order to create dynamic charts. While referencing this example for guidance, I am facing challenges in making the chart react to changes within the store.

Although I can observe changes in the Pinia store data when modified in another component through a reactive form, the chart itself does not update accordingly.

The component used to render the chart includes:

<script setup>
import { storeToRefs } from 'pinia'
import { useStore} from '@/store/pinia-store-file';
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
);  

const store = useStore();

const storeData= storeToRefs(store);
const labels = [...Array(storeData.arr.value.length).keys()];

const data = {
  labels: labels,
  datasets: [
    {
      label: 'Data One',
      backgroundColor: '#f87979',
      data: storeData.arr.value
    }
  ]
}

const options = {
  responsive: true,
  maintainAspectRatio: false
}



</script>

<template>

  <Line :data="data" :options="options" />

</template>

I have attempted wrapping the store variable in ref(), but it seems that I may need to trigger a re-render of the chart. Applying the aforementioned example to a Pinia store state and ensuring updates reflect in the chart has proven to be a challenge.

Answer №1

Instead of setting data directly as a response, it is recommended to use computed properties

You can utilize the following code to resolve this issue:

<script setup>
import { storeToRefs } from 'pinia'
import { useStore} from '@/store/pinia-store-file';
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';
import { computed } from "vue"

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
);  

const store = useStore();

const storeData= storeToRefs(store);

const data = computed(() => ({
  labels: [...Array(storeData.arr.value.length).keys()],
  datasets: [
    {
      label: 'Data One',
      backgroundColor: '#f87979',
      data: storeData.arr.value
    }
  ]
}))

const options = {
  responsive: true,
  maintainAspectRatio: false
}



</script>

<template>

  <Line :data="data" :options="options" />

</template>

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

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

Encountering difficulty with installing node_modules on Express js

Encountered an error while attempting to install node_modules from the package.json file. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Refreshing Rails Views by Periodically Polling the Database

We are currently developing a statusboard to monitor all our external servers. Our database contains information about OS, software versions, and other details that are subject to frequent updates. To ensure real-time visibility of these changes on the web ...

Steps for dynamically adding or removing multiple fields in a form

I am looking to create a form with dynamically added and deleted fields based on user requirements. For example, a person may have multiple phone numbers and email addresses. The goal is to allow users to add more than one phone number or email address if ...

One way to send image data from the front end to the back end using AJAX

Client-Side JavaScript: var userInfo = { 'username': $('#addUser fieldset input#inputUserName').val(), 'email': $('#addUser fieldset input#inputUserEmail').val(), 'fullname': $('#addUser f ...

Strange padding issue found on View component in React Native Web when using Edge browser

While developing a Button in react native for the web, I noticed an unusual padding issue when viewing the button in Edge. Despite my efforts to debug, I have not been able to find a solution. Strangely, the button appears correctly on Android and Firefox. ...

Exploring unescaped XML for handling unicode characters

Currently tackling the challenge of parsing some XML that is not properly formatted. The XML file contains un-escaped ampersands, which goes against the standard rules for XML files. My goal is to extract unicode formatted phrases from this XML file whil ...

ways to undo modifications made to a value within an input field using jquery or javascript

$(document).ready(function () { //Highlight row when selected. $(function () { $('#Cases tr').click(function () { $('#Cases tr').removeClass('selectedRow'); $(this).addClass(&apos ...

Connecting event listeners to offspring elements, the main element, and the entire document

My request is as follows: I have multiple boxes displayed on a webpage, each containing clickable divs and text. When a user clicks on a clickable div, an alert should appear confirming the click. Clicking on the text itself should not trigger any action. ...

The Child Component in React Native Always Shows Undefined Response Status from API

In the code snippet below, I am facing an issue where the status returned by an API call is always showing as undefined in the child component, even though I can see the expected status code when logging it in the parent component. It seems like the child ...

VueJS enables the implementation of a feature that allows users to navigate to

I am currently developing an application that generates a fixed length list based on a nested JSONArray structure. When any element is clicked from the list and if it contains a "sub data" array, the list will then be populated with this "sub data". Essent ...

What is the purpose of Vue emitting and propagating to the parent component?

As a newcomer to Vue, I encountered an issue with my child component. In the code snippet below, I added a validator using the 'emits' property, expecting that if the validation fails, the parent event handler would not be called. However, to my ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

React Native error: encountering the error message "undefined is not an object '_this3.props.navigation()'"

I am encountering an error in the navigationOptions() function when running my React app, but everything is working correctly in the render() function. App.js import React, { Component } from 'react'; import { AppRegistry, View } from 'r ...

Searching for text within a PDF document using the Internet Explorer version 9 browser by

When a link is clicked in our application, it opens a new window with a secure PDF file. We are looking to validate this using Selenium in Ruby. However, we encountered an issue in IE9 where there is no HTML/DOM element for validation. We were able to suc ...

What is the correct way to utilize the BigInt right shift operator and XOR in JavaScript?

After spending the entire day trying to figure out how to shift bits to the right in JavaScript, I realized that my test program written in C language was not giving the correct results for comparison. If anyone can guide me in the right direction, please ...

The power of Ng-show and filtering

What I am aiming for is to display a complete list of cities as soon as the page is loaded. Once a user clicks on a checkbox next to a city, my goal is to utilize ng-show/ng-hide in order to display the results specific to that city while hiding those of ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...

What could be causing my ES6 code to fail compilation post npm install?

Check out my npm module built with es6 on Github here. Within the package.json file, there are scripts designed to ensure proper building of the es6 modules. When using npm publish and npm install within the module's directory, everything works fine. ...