Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'):

Check out the plot image

The odd thing is, the extracted arrays appear to be accurate as seen in the console log observers: View arrays here

I need some help figuring this out. I initially suspected it was a syntax issue, but even after reviewing the ChartJS documentation, I'm unable to pinpoint the problem. Below is the code snippet (I realize that I unnecessarily repeated the 'data' and 'filled' arrays for testing purposes only.):

<template>
<div>
<ModelNavbar/>
          <line-chart v-if="loaded" :data="chartData"></line-chart>
</div>
</template>

<script>
import Vue from 'vue';
import ModelNavbar from '@/components/ModelNavbar';

export default {
  name: 'charts',
  props: ["items"],
  components: {
    ModelNavbar
  },
  data() {
    return {
      loaded: false,
      chartData: '',
      file: null,
      spdMes: [],
      perPage: 5,
      fields: [  {key: 'id', label: 'ID'},
       {key: 'spdMesRpm', label: 'Rotary Speed (Rev/s)'}]
    }
  },
  async created()
    {
      await Vue.axios.get('http://localhost:8002/outputservice/spd/findAll')
            .then((response) =>{
                this.spdMes = response.data.data.items;
                console.warn(this.spdMes);
            });
    },
    async mounted() {
      this.loaded = false
          Vue.axios.get('http://localhost:8002/outputservice/spd/findAll')
           .then((response) =>{
             this.dataList = response.data.data.items;

            this.chartData = {
              labels: this.dataList.map(item => item.id),
              datasets: [
                {
                label: 'Measured Speed',
                data: this.dataList.map(item => item.spdMesRpm)
                }
              ]
            }
            this.loaded = true
            console.warn(this.chartData);
          });
    }
}
</script>

Answer №1

My expertise lies in Vue 2 and the Vue CLI (Single File Components). I recently undertook a personal project involving Vue and Chart.js, where I created sample bar and pie charts. Upon coming across your query, I made modifications to include a sample line chart in my project. The components for this example are provided below.

chart-configurations.js

const sampleLineConfig = {
  type: 'line',
  data: {
    labels: [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July'
    ],
    datasets: [{
      label: 'Sample Dataset',
      data: [],
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    responsive: false
  }
};

export {
  sampleLineConfig
}

App.vue

<template>
  <div id="app">
    <chart-test v-if="dataReady" :chartData="lineChartData" />
  </div>
</template>

<script>
  import ChartTest from '@/components/ChartTest'

  export default {
    name: 'App',
    components: {
      ChartTest
    },
    data() {
      return {
        lineChartData: [65, 59, 80, 81, 56, 55, 40],
        dataReady: false
      }
    },
    methods: {
      getData() {
        this.dataReady = true;
      }
    },
    mounted() {
      // Simulate API call
      setTimeout(this.getData(), 1000);
    }
  }
</script>

ChartTest.vue

<template>
  <div class="chart-test">
    <h3>Chart Test</h3>
    <canvas id="chart-canvas" width="500" height="500" ref="chartref"></canvas>
  </div>
</template>

<script>
  import Chart from 'chart.js';
  import { sampleLineConfig } from '@/chart-configurations.js'

  export default {
    data() {
      return {
        chartObj: null,
        chartConfig: sampleLineConfig
      }
    },
    props: {
      chartData: {
        type: Array,
        required: true
      }
    },
    methods: {
      setChartData() {
        this.chartConfig.data.datasets[0].data = this.chartData;
      }
    },
    mounted() {
      this.setChartData();
      this.chartObj = new Chart(this.$refs.chartref, this.chartConfig);
    },
    // beforeDestroy() {
    //   // This necessary if canvas is reused for a new chart
    //   this.chartObj.destroy();
    // }
  }
</script>

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

The hexagons configuration for tsParticles is experiencing technical difficulties

I'm struggling to implement the tsParticles library (specifically using react-tsparticles) in combination with the latest version of Next.js. However, when I try to use the particle.json file and bind it to the <Particles/> component, the partic ...

Error encountered in React V16.7: The function is not valid and cannot be executed

import React, { useContext } from 'react'; The useContext function is returning undefined. Error Details: Uncaught (in promise) TypeError: Object(...) is not a function Error occurred when processing: const context = useContext(UserCon ...

Using VUE/NUXT to send a random number as a prop to a child component

In my Vue component, I'm struggling to have a consistent randomNumber variable between the template and script tag. One method I tried is using datas: <template> <div :data-number="randomNumber" </template> <script> export defa ...

Tips for preventing a function from being triggered twice during a state change

I'm currently working with a react component that looks like this: const [filter, setFilter] = useState(valueFromProps); const [value, setValue] = useState(valueFromProps); const initialRender = useRef(true); useEffect(() => { if (initialRender. ...

What changes can be made to the HTML structure to ensure that two form tags function separately?

Hey there! I'm currently tackling a web project that involves incorporating two form tags on one page, each with its own distinct purpose. Nevertheless, it appears that the inner form tag isn't behaving as it should. My suspicion is that this iss ...

Develop an outline using D3.js for the clipath shape

After successfully creating a shape with a color gradient, I encountered the need for further customization. If you are interested in this topic, check out these related questions: Add multi color gradient for different points in d3.js d3.js scatter plot c ...

Can you include conditional logic within a switch statement?

I've been using if, else if, and else statements in my code but recently switched to switch statements which have made things much simpler. Now I'm wondering if it's possible to add multiple conditions inside a switch statement, similar to i ...

Improving a lengthy TypeScript function through refactoring

Currently, I have this function that I am refactoring with the goal of making it more concise. For instance, by using a generic function. setSelectedSearchOptions(optionLabel: string) { //this.filterSection.reset(); this.selectedOption = optionLa ...

Tips for inserting a component into a div selector using Angular 2

Could someone please help me figure out how to inject a component into a div selector using a class or id? I'm familiar with injecting components into other components, but not sure how to do it specifically within a div. Any guidance would be greatly ...

I seem to be stuck in an endless loop within React and can't find a way to break free

Currently, I am utilizing the useState() function along with an array errors[] as part of the state and a function setError() to pass the useState() function to child elements for calling purposes: const [errors, setErrors] = useState([]); //-------------- ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

Referencing a JSON object

Here is a JSON list of search terms: [ "halo", [ "halo reach", "halo anniversary", "halo 4", "halo 3", "halo mega bloks", "halo 2", "halo sleepsack", "halo wars", "halo reach xbox 360", "halo combat evolved" ], ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

Using the html5 file reader API in JavaScript to retrieve a file as a binary string and then sending it through an ajax request

I'm attempting to obtain the binary string of files, but I seem to be unable to do so. Why does readAsDataUrl work while readAsBinaryString doesn't? I have posted my code on jsbin and any help would be greatly appreciated. Thank you. Check out ...

What is the best way to determine if any of the objects in an array contain a "completed" property with a value of false using JavaScript and React?

Is there a way to determine if at least one item in an array of objects has a completed property with a value of false using JavaScript and React? Here is an example array of objects: const items = [ { id: "32", jobs: [ ...

React.js: The art of nesting components within each other

One common feature in many template languages is the use of "slots" or "yield" statements, which allow for a form of inversion of control by wrapping one template inside another. Angular offers the "transclude" option for this purpose. Ruby/Rails utilize ...

The preflight request for Firebase Storage CORS did not pass the access control check due to not having an HTTP status of ok

When attempting to upload an image to Firebase Storage, I encountered an error in the Chrome console: Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/v0/b/%22website-admin-c9ce6.appspot.com%22VITE_APP_VERSION%3D0.0.0/o/MYx2YMuRBw ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

Encountering difficulties triggering the click event in a JavaScript file

Here is the example of HTML code: <input type="button" id="abc" name="TechSupport_PartsOrder" value="Open Editor" /> This is the jQuery Code: $('#abc').click(function () { alert('x'); }); But when I move this jQuery code to a ...

Attempting to access a variable from outside the function

I am looking to pass the index variable from mapping to the event change function in my code snippet below: {this.data && this.data.map((item, index) => ( <tr className="table-info" key={index}> <td>{index}</ ...