Chartjs-I would like to show a line bar in chart.js with data automatically fetched from mockapi

1👍

With your Months and myData vars you were wrapping them in another array (the [] around the variable name). Due to that, the chart only saw 1 label and 1 data point, which is not what you want.

I removed the outer [] so that only your arrays are set as the label and data on the configuration.

One more thing I anticipated is that you would deal with long label names (like Mon Dec 17 2018 16:36:04 GMT+0100 (Central European Standard Time)) which wouldn’t look good on your graph.

To fix that I shortened the date by creating a new date obj and using toLocaleString on it. I also read that if a label is represented as an array instead of a single string then each part would be on a new line.

This is where .split(“,”) can help. toLocaleString() returns, for example, the string "12/20/2018, 12:00:00 PM" so the split function would split that string wherever there is a comma and push the result to an array. The resulting array will have index 0 as 12/20/2018 and index 1 as 12:00:00 PM so each would be on its own line in the graph.

const myData = ["60", "80", "5", "100", "60"];
const months = ["Mon Dec 17 2018 16:36:04 GMT+0100 (Central European Standard Time)", "Mon Dec 17 2018 17:36:34 GMT+0100 (Central European Standard Time)", "Thu Dec 20 2018 09:34:18 GMT+0100 (Central European Standard Time)", "Thu Dec 20 2018 09:37:16 GMT+0100 (Central European Standard Time)", "Thu Dec 20 2018 12:41:51 GMT+0100 (Central European Standard Time)"];

let newMonths = months.map(function(date){
  return new Date(date).toLocaleString().split(",");
});

let myChart2 = document.getElementById("myChart2").getContext('2d');
let DonationChart2 = new Chart(myChart2, {
  type: 'bar',
  data: {
    labels: newMonths,
    datasets: [{
      label: 'Amount',
      data: myData
    }]
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>

<canvas id="myChart2" width="1000" height="900"></canvas>

Leave a comment