"Troubleshooting: Vue ChartJS Line Chart fails to show data

Hey there! I'm currently working on integrating Chart.js with the vue-chartjs wrapper to build a Line Chart using data retrieved from my API. The data is being successfully logged to the console without any errors, but for some reason, the Line Chart itself is not displaying on the browser. Instead, there's just a lot of white space where the canvas tag should be. Oddly enough, I can create a doughnut chart with no issues, just not this particular line chart. Any guidance or assistance on this matter would be highly appreciated! I'm referencing the Chart examples available at for the LineChart component

IndexView.vue

<script setup>
import axios from 'axios'
import { onMounted, reactive } from 'vue'
import LineChart from '@/components/LineChart.vue'


const data = reactive({
  user: null,
  totals: null,
  checkins: null
})
const state = reactive({
  loading: true
})
const charts = reactive({
  doughnutConfig: null,
  lineConfig: null
})
onMounted(async () => {
  // load data from store and api
  data.user = await userStore.fetchUser()
  const user_resp = await axios.get(...)
  data.totals = user_resp.data.totals
  data.checkins = user_resp.data.check_ins
  state.loading = false

  // create line chart
  var dates = []
  var ratings = []
  var length = data.checkins.length < 10 ? data.checkins.length : 10
  for (var i = 0; i < length; i++) {
    dates.push(data.checkins[i].date)
    ratings.push(data.checkins[i].rating)
  }

  console.log(dates) // [ "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-04T00:00:00", "2022-09-05T00:00:00" ]
  console.log(ratings) // [ 5, 5, 3, 2, 4 ]

  charts.lineConfig = {
    data: {
      labels: dates,
      datasets: {
        label: 'Ratings by date',
        data: ratings,
        backgroundColor: '#f87979'
      }
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        }
      }
    }
  }
})
</script>
<template>
  <LineChart
    v-if="charts.lineConfig"
    :chart-options="charts.lineConfig.options"
    :chart-data="charts.lineConfig.data"
    :width="400"
    :height="300"
  />
</template>

LineChart.vue

<script setup>
import { defineProps } from 'vue'
import { Line } from 'vue-chartjs'
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  LineElement,
  LinearScale,
  PointElement,
  CategoryScale
} from 'chart.js'

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

const props = defineProps({
  chartData: {
    type: Object,
    required: true
  },
  chartOptions: {
    type: Object,
    required: true
  },
  chartId: {
    type: String,
    default: 'line-chart'
  },
  width: {
    type: Number,
    required: true
  },
  height: {
    type: Number,
    required: true
  }
})
</script>

<template>
  <Line
    :chart-id="props.chartId"
    :chart-data="props.chartData"
    :chart-options="props.chartOptions"
    :width="props.width"
    :height="props.height"
  />
</template>

Answer №1

If you're experiencing a situation where a chart isn't displaying, it's likely due to an issue with the data configuration.

Upon reviewing your data config, it appears that the datasets option is being defined as an object when it should actually be an array.

 data: {
      labels: dates,
      datasets: { // <--- should be an array.
        label: 'Ratings by date',
        data: ratings,
        backgroundColor: '#f87979'
      }
    },

To resolve this, it should be structured as follows:

 data: {
      labels: dates,
      datasets: [{
        label: 'Ratings by date',
        data: ratings,
        backgroundColor: '#f87979'
      }]
    },

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

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

Custom geometry in Three.js raycaster detects incorrect object

I am facing a challenge with the default cube's appearance in wireframe mode, as it is made up of triangles instead of squares. To combat this, I created my own geometry which looks satisfactory. However, I have noticed that the raycaster does not fu ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

Tips for ensuring an HTML element remains within defined boundaries

Currently working on a visualization tool for search algorithms using React, I've encountered a minor issue when moving the start or end nodes. Upon clicking and dragging the mouse across the grid, the nodes adjust accordingly until reaching the grid& ...

Color scheme for navigation bar carousel item background color

I have a navigation bar and carousel within the same section. I want to change the background color of both the navigation bar and carousel item when the carousel indicator becomes active. Any suggestions on how to achieve this using a jQuery function? H ...

Optimizing React components by efficiently updating props without triggering unnecessary renders

As I delve into learning React, I've encountered a challenge with using a component to display details of a selected item in a table. The issue arises when clicking "Next" on the paginated table, causing the state to update and re-render the component ...

The date format is malfunctioning -> Error: The date provided is not valid

My goal is to convert the date format from 2022-01-17T21:36:04.000Z to January 18th using the npm package, dateFormat. I found success with the following code snippet: const date = dateFormat("2022-01-17T21:36:04.000Z", "mmmm dS"); However, when trying t ...

What is the best way to fetch the most recent article from every category using mongodb?

I am currently working with the following article schema: var articleSchema=new Schema({ id : Number, title : String, sefriendly : String, created : Date, categories: [ { id: Number, name: String, ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

Encountering an issue in next.js with dynamic routes: getting a TypeError because the property 'id' of 'router.query' cannot be destructured since it is undefined

I am working on creating a dynamic page in next.js based on the ID. Here is the basic structure of my project: File path: app/shop/[id]/page.tsx This is the code snippet: "use client" .... import { useEffect, useState } from 'react' ...

Developing an interactive input field using JavaScript's Document Object Model (DOM)

I am struggling with creating an editable text field using JavaScript. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function create ...

Sending a parameter value from a blade view in Laravel to a controller: tips and tricks

What is the best way to pass the value "{{$ item-> id}}" to a method in a controller? For example, if we have show.blade.php with the value: "{{$ item-> id}}" In MyController.php, how can we utilize this value within the method: public function ...

What is the process for transforming a block of plain text into a formatted text with multiple paragraphs while tracking the word count

I am faced with the task of transforming a simple text consisting of 5000 words into multiple paragraphs, each containing 1000 words. Is there a way to accomplish this? If so, I would greatly appreciate any guidance or assistance you can provide. ...

What is the best way to transfer data from processing.js to a rails application?

I am working on a basic canvas project using processing.js, and I am wondering how I can transfer data from my Rails application to Processing.js. void drawBox(int bx, int by, int bs, int bs){ strokeWeight(3); stroke(50,50,50); // Test ...

I am facing an issue with my $.getJSON() script not functioning as expected

Having trouble getting my JSON / AJAX script to work. I've searched everywhere but can't find a clear explanation of how to use $.getJSON. Can someone please help me out and explain why my code isn't functioning? I suspect the issue lies wit ...

JQuery and Fancybox causing issues when triggered on Internet Explorer 8

I am experiencing an issue with my jQuery code on my webpage. It works perfectly fine in Chrome, but I encounter an error in Internet Explorer 8 specifically in the trigger('click') line. $('#btnd16').click(function(e){ var iiid = ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...