MX313
MX313

Reputation: 153

chartjs & asp.net: Cannot read property 'labels' of undefined

I have been through all the posts regarding this issue yet I can not fix it.

My chartjs line chart gets created fine. I am trying to test updating it (adding data) but i'm stuck on the chart.data.labels.push(labels) as it states the object is undefined in the console. Yet on the console, the line before, I write the id of the object and it is correct so it has the ref.

Any thoughts?

Chart is created fine

$(function () {
    LoadChart();
});

function LoadChart() {
    var ctx = document.getElementById('myChart');
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['9:30', '9:31', '9:32', '9:33', '9:34', '9:35'],
            datasets: [{
                label: 'RSI',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
           title: {
                display: true,
                text: 'Custom Chart Title'
            }
        }
    });
}

Error When trying to update the chart

$.connection.redisHub.client.addData = function (chartID, labels, data) {
    var chart = document.getElementById(chartID);
    console.log("chart: " + chart.id);
    chart.data.labels.push(labels);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(data);
    });
    chart.update();
}

Console Output You can see it correctly writes 'chart: myChart' to the console showing we have the object ref. correct. enter image description here

asp code calling the js function (all works well here)

string[] labels = { "9:36", "9:37" };
int[] data = { 9, 10 };
Clients.All.addData("myChart", labels, data); 

html : all is well here

<div class="col-sm-8">
    <canvas id="myChart" width="400" height="200"></canvas>
</div>

Thank you in advance

Upvotes: 2

Views: 4447

Answers (1)

timclutton
timclutton

Reputation: 13004

var chart = document.getElementById(chartID); will return the canvas element, which is not an instance of Chart.js, so all of the subsequent code is invalid.

You need to use myChart from the LoadChart() function as this is a Chart.js instance (returned at instantiation). The simplest way to do this is to move the variable definition to a higher scope so that it is available to your update function.

Without knowing how your code is structured it's difficult to give a working example, but here's a simplistic example of what I mean:

var myChart;

$(function () {
    LoadChart();
});

function LoadChart() {
    var ctx = document.getElementById('myChart');
    myChart = new Chart(ctx, {
        type: 'line',
    ...
}

$.connection.redisHub.client.addData = function (chartID, labels, data) {
    myChart.data.labels.push(labels);
    ...
}

Upvotes: 1

Related Questions