5

I have an issue generating a chart with CanvasJS.

Basically I get the data from the API, I can see and check the JSON array but when I'm going to generate the dataPoint for the graph I get 2 errors: data invalid on the data field and NaN on the value field.

Can someone give me a hint?

// Fetching the data
fetch('https://example.com/my/endpoint').then(response => {
  return response.json();
}).then(data => {
  // Work with JSON data here
 var jsonData = data;
 // Generating Data Points
 var dataPoints = [];
 
for (var i = 0; i <= jsonData.length - 1; i++) {
    dataPoints.push({ y: new Date(jsonData[i].source_ts), x: Number(jsonData[i].xyzw) });
    console.log(dataPoints);
}

var chart = new CanvasJS.Chart("chartContainer", {
    data: [
        {
            dataPoints: dataPoints,
            type: "line",
        }
    ]
});

chart.render();
}).catch(err => {
 throw new Error( 'Impossible to get data' );
});

Cheers

1 Answer 1

2

You were not intreating correctly over data due to which you were getting y:null and x:NaN.

Content inside data is array of objects inside an array i.e. [[{}, {}, {}...]]so you need to iterate accordingly.

Use this code:

  data.forEach(function(array) {
    array.forEach(function(arrayItem) {
      dataPoints.push({
        y: new Date(arrayItem.source_ts),
        x: Number(arrayItem.renewablesobligationconsumption)
      });
    });
  });

Below is complete working example. Now your dataPoints is ready, you can use it anywhere you want:

// Fetching the data
fetch('https://example.com/my/endpoint').then(response => {
  return response.json();
}).then(data => {

  // Generating Data Points
  var dataPoints = [];

  data.forEach(function(array) {
    array.forEach(function(arrayItem) {
      dataPoints.push({
        y: new Date(arrayItem.source_ts),
        x: Number(arrayItem.xyzw)
      });
    });
  });
  
 console.log(dataPoints);

  var chart = new CanvasJS.Chart("chartContainer", {
    data: [{
      dataPoints: dataPoints,
      type: "line",
    }]
  });

  chart.render();
}).catch(err => {
  throw new Error('Impossible to get data');
});
<br/>
<!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->

<div id="chartContainer" style="height: 300px; width: 100%;"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Downvoter please mention the reason of downvoting an already accepted answer. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.