"Trouble with Vue chart.js: Data not loading properly when the page

I'm currently working on a project that involves using vue-chartjs within the Laravel framework. I've encountered an issue where the data doesn't load upon initial page load. However, if I click on the Legend three times, the data eventually appears.

You can see the problem in action in this gif:

Here is my code:

<template>
    <Chart :chartData="this.data" :width="800" :height="500"></Chart>
</template>
<script>
    import Chart from './Chart.vue';

    export default {
      name: 'home',
      components: {
        Chart
      },
      data() {
        return {
            data: {},
            weights: [],
            dates: []
        }
      },
      mounted () {
        this.render()
      },
      methods: {
        render() {
            self = this
            axios.get('/api/data')
              .then(function (response) {
                for (var i = 0; i < response.data.data.length; i++) {
                    self.weights.push(response.data.data[i].kg)
                    self.dates.push(response.data.data[i].created_at)
                }
                console.log(response)
              })
              .catch(function (error) {

                console.error(error);
              });
            // Update base render method with actual data.
          self.data = {
            labels: self.dates,
            datasets: [
              {
                label: 'Data One',
                data: self.weights,
              }
            ]
          }
        }
      }
    }
</script>

Chart.vue:

<script>
    import VueCharts from 'vue-chartjs'
    import { Bar, Line, mixins } from 'vue-chartjs'
    import moment from 'moment'
    import axios from 'axios'
    export default {
      extends: Bar,
      mixins: [mixins.reactiveProp],
      props: ['chartData', 'options'],
      data() {
        return {

        }
      },
      mounted () {
        this.renderChart(this.chartData, this.options)
      },
      methods: {
      }
    }
</script>

Answer №1

It appears that the issue lies here:

  myObject = {
        labels: myArray,
        datasets: [
          {
            label: 'Set One',
            data: myValues,
          }
        ]
      }

The object is referencing itself so myObject = this.object. This is directly assigning to the components' data property.

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

Is it possible to convert the useMemo function into a useReducer hook implementation?

While I've figured out how to switch from using useState to useReducer, I'm now curious if there's a similar approach for transitioning from useMemo? I've been troubleshooting some code that's causing unnecessary renders because o ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

The directive stops functioning properly following the minification process

Here is a directive that I am working on: var tonicswitch = angular.module('tonicswitch', []).directive('multiSelectTonics', function(){ return { restrict: 'E', scope: { items: '=', ...

"Enhance your online communication with Webrtc video and audio chat using Laravel and Vue.J

Currently, I am working on setting up a video and voice chat using webrtc. The main issue I am encountering is that the audio of both participants is looping back to them. While we can hear each other clearly, we shouldn't be able to hear our own voic ...

Pop-up that appears based on the location of the mouse click

I am looking for a rollover popup that is triggered by the location of a mouse click. I am unable to use a CSS absolute positioned div inside a relative one because it causes my popup to be cropped due to overflow:hidden being set for layout purposes. The ...

Having Trouble with Jquery UI Date Picker?

I have included my form code below. <div class="threeleft second" id='displayallformshow' style="float: none;width: 80%;padding:10px;"> <form action="investor_submit.php"> <div class='formdiv'> ...

Watchify fails to detect any modifications in the directories above

I currently have multiple apps stored in a single folder with a shared dependency. /app/app1/src/main.js /app/app2/src/main.js /app/app3/src/main.js /common/tools.js Each of these apps has its own instance of Watchify running, and any changes trigger a r ...

An array of dictionaries that are the same except for one dictionary containing an unspecified key

A while ago, I wrote some sample code to generate Euler diagrams from an array of dictionaries. Strangely enough, it only works when the array is explicitly defined in my .js file; using input from a .json file to construct it incrementally does not yield ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...

When extracting a value from an HTML textarea that contains multiple lines of text inputted by the user, the JSON becomes invalid

Here is the JSON format I am working with: { questionID: int studentAnswer: "String" } The issue I am facing is that the studentAnswer field is currently only capable of holding input from a single line in an HTML textarea. If I input text that spa ...

Unexpected error: JSON data at line 1 column 1 of the JSON data is incomplete

I've encountered an issue with my script related to a JSON response error. Below is the code snippet in question: $(document).ready(function() { $('#btndouble').click(function(){ var address = $('#btcaddress').val(); ...

What methods are available to access a variable beyond the event listener scope?

Is there a way to create a JavaScript code that generates a list of selected pictures, including the thumbnail, filename, and filesize of each picture? I've been trying, but it seems like the event listener isn't able to access the filename and f ...

What is the process for programmatically injecting a search query to activate the places_changed event for the Google Maps API?

Currently, I am working on a search page that includes a location input field. My goal is to automatically populate this input with a query if a user reaches the page from another source with a search query. Additionally, I want to trigger a place change e ...

The issue of receiving a 500 error when making a POST request in node.js

I have created my own unique REST API that utilizes an NLP API internally. I need to post data on their URL, but unfortunately I am encountering an error that is causing my API to return a 500 error to the frontend. Below is a snippet of my server.js code ...

Using arrow functions in Typescript e6 allows for the utilization of Array.groupBy

I'm attempting to transform a method into a generic method for use with arrow functions in JavaScript, but I'm struggling to determine the correct way to do so. groupBy: <Map>(predicate: (item: T) => Map[]) => Map[]; Array.prototype ...

Enhancing Chart Accessibility with Highcharts in VUE.js

We have a client requesting full-screen readability and keyboard navigation for their website (which is hosted on Squarespace and we created a Vue plugin for them). I have successfully implemented these features in all areas of their site, including Leafl ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

I encountered a problem with iteration where the results appeared perfectly fine, but upon rendering at the component level, the same field loaded with the last object instead

I am facing an issue with rendering the component level when it loads. After clicking on edit and calling the edit function, the data is properly loaded in console and all objects are shown. However, they do not render on the page level. Below is the code ...