Initializing multiple instances of vue-chartNote: The unique text

I am looking to implement multiple vue-chart.js graphs, each refreshing (adding a new data point) every 5 seconds. The data comes from a sensor and is passed using props (I am developing the UI for a node-red application, but this detail may not be relevant to the issue at hand).

While I successfully got one graph working correctly, I encountered an issue when trying to display values in two separate graphs simultaneously. Instead of each graph displaying its respective values, both graphs were updating with the same values.

You can see the issue demonstrated here.

What confuses me is that when I log this.myChart in the adddata method, it shows the "correct" graph (with different id and context). Even though I believe I have created individual instances of the graphs, I cannot seem to add data to only one of the graphs.

Since I do not use Vue frequently, I might be overlooking something important. Any insights would be greatly appreciated!

Component Test.vue

<template>
  <div>
    <canvas :id="name"></canvas>
  </div>
</template>

<script>
import Chart from "chart.js";

const chartSetting = {
  type: "line",
  data: {
    datasets: [
      {
        label: "setpoint",
        data: [],
        borderColor: "blue",
        borderWidth: 3,
      },
    ],
  },
  options: {},
};

let interval;

export default {
  name: "test",
  data() {
    return {
      myChart: null,
      chartSetting: chartSetting,
    };
  },
  props: ["id", "name", "setpoint"],
  methods: {
    adddata(setpoint, time) {
      this.myChart.data.datasets[0].data.push(setpoint);
      this.myChart.data.labels.push(time);
      this.myChart.update();
      console.log(`now printing ${setpoint} to this graph:`);
      console.log(this.myChart);
    },

    createChart(chartId, chardData) {
      const ctx = document.getElementById(chartId);
      // Save reference
      this.myChart = new Chart(ctx, {
        type: chardData.type,
        data: chardData.data,
        options: chardData.options,
      });

      interval = setInterval(() => {
        let date = new Date();
        let seconds = date.getSeconds();
        this.adddata(this.setpoint, seconds);
      }, 5000);
    },
  },

  mounted() {
    this.createChart(this.name, this.chartSetting);
  },
};
</script>

App.vue

<template>
  <div id="app">
    <p>
      graphs get new data from 2 different sensors every 5 seconds. Here
      simulated as "6" and "3"
    </p>
    <h3>this graph should only show 6</h3>
    <test name="grap1" id="1" setpoint="6" />
    <h3>this graph should only show 3</h3>
    <test name="grap2" id="2" setpoint="3" />
  </div>
</template>

<script>
import Test from "./components/Test";

export default {
  name: "App",
  components: {
    Test,
  },
};
</script>

Answer №1

The setting for the chart remains consistent across all components because it is established once the component module is loaded.

The purpose of data being a factory function is to generate a fresh data object for each instance, ensuring that there is no sharing between instances.

The code block should be:

  data() {
    const chartSetting = ...

    return {
      myChart: null,
      chartSetting: chartSetting,
    };
  }

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

Demystifying Iron Ajax: Unraveling the process of parsing an array of JSON objects from a successful

When making an AJAX call to the server, I receive a response in the form of an array of objects as JSON. [{"dms":[{"serialNo":"EG0022","status":"running","firmwareStatus":"ok","latitude":37.8688,"longitude":-144.2093,"toolType":1},{"serialNo":"EG0022","st ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

Using an `<img>` element as an event handler in a JavaScript function

I'm having trouble setting up a click handler for the search field in my project. I've tried using on() with an img or class, but it's not working as expected. When adding the image using the code below: jQ('#psc').append('&l ...

Choosing particular contenteditable divisions using jQuery

Consider the following HTML structure for a specific type of blog post editor: <div class="entry"> <div class="title" contenteditable="true"> <h2>Title goes here</h2> </div> <div class="content" contenteditable ...

What is the best method for transferring images to a node.js server using Axios?

Is there a method to utilize axios for sending an array of images or a single image to node? My current axios code (implemented in react js on the frontend): onFormSubmit(event){ event.preventDefault(); let payload = this.state; console.log(" ...

Guide on how to implement a file upload feature using only JavaScript and the FileReader API

Allow me to explain the issue I'm facing. To give you some context, I've been working on a forum web application. Lately, I've been trying to enable users to choose a photo from their local file system during sign up. The idea is that once a ...

Yelp API call resulting in an 'undefined' response

When attempting to make an API call using the yelp-fusion, I noticed that the logged result is showing as undefined. It seems like this issue might be related to promises or async functions. It's important for me to maintain this within a function sin ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Including jQuery in an Angular project generated with JHipster

I am facing a challenge with integrating jQuery into my Jhipster Angular project as a newcomer to Jhipster and Angular. My goal is to customize the theme and appearance of the default Jhipster application, so I obtained a theme that uses a combination of ...

Console is displaying a Next.js error related to the file path _next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json

I keep getting an error in the console on my Next.js website. GET https://example.com/_next/data/QPTTgJmZl2jVsyHQ_IfQH/blog/post/21/.json net::ERR_ABORTED 404 I'm puzzled as to why this is happening. Could it be that I'm mishandling the router? ...

Converting HTML to PDF using Node and Express

Searching for a way to directly render a webpage as a PDF in the browser through Express. Essentially, I want to convert the page into a PDF without saving it. I came across a module that can convert HTML or a URL into a PDF format. https://github.com/ma ...

Unable to store simple HTML file using service worker

I am working on a webpage that displays a message when the user is offline. However, I am facing an issue with my service worker while trying to cache the page. The Chrome console always throws this error: service-worker.js?v=1:1 Uncaught (in promise) D ...

Showing additional content in an alternative design

I'm currently facing an issue with the "load more" post button on my Wordpress site. I've designed a unique grid layout for the category page, with a load more button at the bottom. However, when I click the button to load more posts, they appear ...

receiving a null value from a dropdown selection in react native

As a beginner in learning react native, I am eager to retrieve the selected value from a dropdown in react-native. This is my constructor constructor(props){ super(props); this.state = ({ PickerSelectedVal : '' ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Error Encountered in Next.js: PDFtron Webviewer - Troubleshooting

I'm currently working on a website that incorporates a dynamically imported PDF viewer within the page. When running the code locally, everything operates smoothly with no errors. However, when executing the "npm run build" command, I encounter the fo ...

Generating a three-dimensional sphere from flat coordinates with the help of sine and cosine functions

I am trying to achieve mapping a set of 2D coordinates to a 3D surface of a sphere. To accomplish this, I am starting with an array of xy coordinates. Using the following loops, I am generating 20*20 xy coordinates ranging from 0 to 1 on each axis: var p ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...