The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data.

https://i.sstatic.net/RD77S.png

My initial suspicion is that maybe the options are not being passed for the lines, but it seems like dataCollection is not being populated, similar to every other type of chart. I am fairly new to Vue (only a few hours of experience), so it could be related to updating the state?

Languages.js

import { Line, mixins } from 'vue-chartjs'
//const { reactiveProp } = mixins

export default {
  extends: Line,
  //mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options)
  }
}

StatsSection.vue

<template>
<!-- Stats Section -->
<div class="stats-wrapper" style="margin: 15px 0; padding: 15px;">
  <languages :chart-data="datacollection"></languages>
</div>
</template>

<script>
import Languages from './charts/Languages.js'

export default {
  components: {
    Languages
  },
  data() {
    return {
      datacollection: {}
    }
  },
  mounted() {
    this.fillData()
  },
  methods: {
      fillData () {
        this.datacollection = {
          labels: [80, 12],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [40, 60]
            }, {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [72, 43]
            }
          ]
        }
      }
    }
}
</script>

Answer №1

The reason for this issue is due to the fillData() method being called in the mounted hook of your code. When the chart is initially rendered, it uses an empty data object which results in an empty chart.

Since chart.js is not reactive, the data is only filled after the chart has been rendered, causing the chart to remain empty.

Possible Solutions:

  • Provide a pre-filled data object to the chart instead of relying on the fillData method
  • Alternatively, consider incorporating the reactiveProp mixin into your code

Answer №2

After realizing that the gridlines were not displaying because I forgot to pass options for them, everything started making sense. The example code I was following assumed that the options were already set, which led to my confusion.

Languages.js

import {
  Bar,
  mixins
} from 'vue-chartjs'

export default {
  extends: Bar,
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  data() {
      return {
          options: { 
              scales: {
                  yAxes: [{
                      ticks: {
                          beginAtZero: true
                      },
                      gridLines: {
                          display: true
                      }
                  }],
                  xAxes: [{
                      gridLines: {
                          display: false
                      }
                  }]
              },
              legend: {
                  display: true
              },
              responsive: true,
              maintainAspectRatio: false
          }
      }
  },
  mounted() {
      this.renderChart(this.chartdata, this.options)
  }

}

https://i.sstatic.net/HpqVd.png

Answer №3

To fix the issue, make sure to invoke your fillData() function inside the created(){..here...} hook rather than in the mounted(){} hook within your StatsSection.vue file. By doing this, the created hook will be executed before mounted, ensuring that your datacollection variable is not null during the initial load.

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

Trigger a keypress event following the activation of a button

I've been trying to simulate the press of the backspace key on the keyboard after clicking a button, but all my attempts have been unsuccessful. Here is the code I'm using: function rtf(){ document.getElementById("u0u").focus(); $('#u0u ...

nodejs express routing issue resulting in not found error

I recently started a new node project and wanted to enhance my route adding capabilities. In the past, I only went one level deep with folders, but this time I wanted to go further. To achieve this, I created a recursive function that adds routes and navig ...

The dropdown options for the input type file in Vuejs PWA are not appearing

I have created a Vue.js progressive web app that allows users to easily upload images from their mobile phones. While the app typically functions well, there is an issue where upon downloading the app to the homescreen, the image upload feature sometimes b ...

Verifying website responsiveness using Puppeteer

Looking to create a script that can determine if a webpage has a responsive design? Wondering how to go about it? Well, it's quite simple. In responsive websites, elements like divs, spans, footers, headers, and sections typically adjust to fit the s ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Exploring the functionality of Material-UI's TextField component through role-based testing with React

I currently have some components that contain mui TextFields, and there are two specific scenarios for these components: One TextField is meant for LicenseCode and does not require a label. Additionally, there are several TextFields generated using t ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

Can you please provide instructions on how to expand the view in the title bar for a JavaScript/CSS/HTML UPW project?

Struggling to integrate the title bar in a UWP project using JavaScript/CSS/HTML and having trouble accessing the necessary APIs. Came across a custom helper class written in c++ in UWP samples on Github, but unable to reference it in my javascript code. H ...

Issue with Attaching Click Event to Dynamic Div Elements

I've implemented divs with a Click Event triggered by a value entered in a text box. See an Example Here Upon opening the page, clicking any rows will trigger an alert. However, if you change the value in the text box (Enter Number) and click load, ...

Does the functionality of JSON.parse include recursion?

After receiving a JSON string in response, I parse it as follows: ring = JSON.parse(response); However, although ring becomes an object, the property ring.stones is only a string when it should also be an object. To address this issue, if I execute: ri ...

WebGL annotations failing to display on the webpage

I'm currently working on displaying a 3D model using Three.js in a web browser and looking to incorporate annotations like the ones shown in this Sketchfab model: Interactive 3D Test. I came across a helpful guide at this link, but I'm facing iss ...

How to retrieve the present value from an array using AngularJS

Struggling to assign the current user from my list Here is my array after submitting the form [{"name":"Erich","surname":"Josh","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096c67497a7a276a6664">[email prot ...

Terminate the connection with nginx abruptly

Is there a way for nginx to immediately close the TCP connection once the request has been completed? ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

Having trouble making the JavaScript mouseenter function work properly?

Hi there, I'm having trouble with this code and I can't figure out why it's not working. $('#thumbs > li').mouseenter(function() { $(this).find("div").fadeIn(); }).mouseleave(function(){ $(this).find("div").fadeOut(); ...

Displaying the chosen option from the V-menu in a different section of the application. Utilizing Vuetify

I'm working with a v-menu that has multiple options. I want to be able to display the selected option in another section of my application within the same component. Even though I attempted to use v-model for this purpose, it doesn't seem to work ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

I'm having trouble resolving the issue in my React App after attempting to export a functional component. How can I troubleshoot and

Since the first week of this online course on Coursera.org, I've been struggling to get my React app to display. Even after watching videos and revising the code multiple times based on Google search results, I couldn't make it work. Despite seek ...

Display exclusively the chosen option from the dropdown menu

I am facing an issue with the select input on my webpage. Whenever I try to print the page, it prints all the options of the select instead of just the one that is selected. Can someone please guide me on how to modify it so that only the selected option ...

Modify the placeholder HTML once a username has been submitted

In order to maximize efficiency, I have included an input box with a placeholder that reads: <input id="username-search" placeholder="explore another user's work"> Once the username is entered, I want to modify the placeholder text to somethin ...