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

Turn off the "interaction failed" message in discord.js

When an interaction, such as a button click, is left unanswered, Discord will show "interaction failed" in the client. The expected action: inter.reply('stuff') My preferred action: inter.channel.send('stuff') I am not receiving an e ...

Interactive sidebar component with navigation and animated section markers

For weeks, I've been attempting to create a navigation sidebar similar to the ones shown in these images: Even though getbootstrap.com/components offers appealing navigation sidebars, I have not found a built-in component in their library. This has m ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

After a short delay, make sure to open a new tab when clicking to bypass any popup blockers without relying on Ajax technology

Before you downvote, please consider my rationale. I am in the process of developing a web-based educational project that includes an art section. When a user clicks on a button, an element containing a picture of an art piece appears. I then want to open ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

What could be causing the image file input to appear sideways or flipped?

I am currently working on a Vuejs component that allows users to select a file from their local system. Once the user selects an image, it is previewed in a div. However, I have noticed that some images appear 'flipped' sideways automatically, es ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

What is the best approach to link an HTML document to a MySQL Workbench server utilizing JavaScript, Ajax, and PHP?

On my HTML page, users can enter the name of a movie and if it is found in the database, the name will be displayed. I am attempting to establish a connection to the MySQL Workbench Server using JavaScript, Ajax, and PHP. This is what I have implemented s ...

Verifying the existence of a user in my mongodb database before adding a new user to avoid multiple registrations with the same email address

Attempted to use Express, I am in the process of creating a .js file that manages POST requests and checks whether a user already exists before adding them to my MongoDB database. I set up two separate MongoClient connections for different scenarios: one t ...

Tips for adjusting div content to fit a fixed height on all devices

Looking to adjust the size of the #left-content div based on the height of the window, while ensuring that all content is visible within the fixed #left-bg. However, when viewing on mobile or tablet devices, the content appears hidden. .left-bg{ backgro ...

Discover the method of extracting parameters from an event in Vuetify Vue.js

I am currently delving into the world of Vuetify and Vue.js, and I have a question regarding retrieving parameters when clicking on my treeview: For example, in the Chrome console with the Vue extension installed, I see: vue event update:active This pro ...

There seems to be an issue with connecting to the local server at https://localhost:3000/socket.io/ while using a

I am currently working on a Node.js project where I have a client.js for client-side code, and a server.js on a remote server using sockets to communicate over port 3000 In addition, Apache is running on port 80, with a ProxyPass configuration in place to ...

Securing data in AngularJS $http.post requests: Best practices

While working on $http.post requests for my app's backend, I noticed a security issue. When inspecting the data using tools like firebug in Firefox, I can see all the information being sent. Is it possible for third parties to intercept this data? Th ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Automatically switch slides and pause the carousel after completing a loop using Bootstrap 5 Carousel

Seeking assistance with customizing the carousel functionality. There seems to be some issues, and I could use a hand in resolving them. Desired Carousel Functionality: Automatically start playing the carousel on page load, and once it reaches the end of ...

The functionality of AngularJS ng-click is disrupted by the presence of {{$index}}

Having an issue with AngularJS where using $index breaks the ng-click function. This issue arises within a div utilizing ng-repeat, the repeat code is functioning correctly... <a class="accordion-toggle" data-toggle="collapse" data-parent="#acc{{$inde ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...

Monitor the output of a spawned process that is currently in a state of awaiting user input

In my Swift program, I am logging information to the stdout while waiting for a termination signal of \n. The input is requested immediately upon starting and the info is logged 1~2 seconds later: fetchAndLogDataInBackground(); // will print some dat ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

Deliver feedback from NodeJS Server to JavaScript on the client side

I have set up an HTTP server in NodeJS by utilizing the http.createServer(...) method. In my client-side JavaScript file, I sent a query using the POST method to the localhost URL. The server effectively received the data from the client, but now I am enco ...