Why prettier put a comma ',' at the last element of the object - javascript

In Visual studio code, When I am using chart.js in my app, prettier always put a comma at the end of the last data of the object 'label'. I think, it's create a bug which unable to show my chart on my browser. it show blank. Code is given bellow.
let massPopChart2 = new Chart(myChart2, {
type: "bar", // bar, horizontalBar, pie, line, doughnut, radar, polarArea
data: {
labels: [
"1st Day",
"2nd Day",
"3rd Day",
"4th Day",
"5th Day",
"6th Day",
"7th Day",
],
},
});
can anyone help me figure out why this happening?

JavaScript has allowed trailing commas in array literals since the
beginning, and later added them to object literals (ECMAScript 5) and
most recently (ECMAScript 2017) to function parameters.
This is a relatively new change in syntax, but the basic idea is that by putting a comma on each line allows for:
Easier to add an item or re-order items. Before you always had to check the trailing comma and make sure it was present or removed depending on location.
Removes the need to have one line item be special because it lacks the ,.
Allows for cleaner Git diffs.
You can read up on the full documentation if you like - it goes into further detail:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas
As far as the issue with your chart not displaying, unless you are using a very old browser, a trailing comma should not cause an error/information to not display.

You need to update the configuration of prettier extension.
There are two ways. Below one is mostly used.
Create a .prettierrc file at the root of your project and
specifying the below configuration.
{ "trailingComma": "es5" }
In order to honor the configuration make sure to enable the below
setting in vs code configuration.
"prettier.requireConfig": true

Prettier adds those commas at the end just because if you wanna add another data after that you don't need to type a comma. it does the same for semicolons(;).
you got the error because you haven't provided datasets.
data takes an object which contains labels & datasets values.
{/* <canvas id="myChart" width="400" height="400"></canvas> */}
// var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['1','2'],
datasets: [
{
label: '1st',
data: '120',
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.transparentize(Utils.CHART_COLORS.red, 0.5),
},
{
label: '2',
data: '240',
borderColor: Utils.CHART_COLORS.red,
backgroundColor: Utils.transparentize(Utils.CHART_COLORS.blue, 0.5),
}
]
},
// options: {
// indexAxis: 'y',
// elements: {
// bar: {
// borderWidth: 2,
// }
// },
// responsive: true,
// plugins: {
// legend: {
// position: 'right',
// },
// title: {
// display: true,
// text: 'Chart.js Horizontal Bar Chart'
// }
// }
// },
// };
you can know more about it on official docs https://www.chartjs.org/docs/latest/charts/bar.html

Related

Initialize several charts in a loop

On my page, I want to show multiple charts that are loaded via ajax. So I get html that is something like this:
<h4>Chart 1</h4>
<canvas data-type="bar" data-labels='["Label 1", "Label 2"]' data-data='[10,20]'></canvas>
<h4>Chart 2</h4>
<canvas data-type="pie" data-labels='["Label 3", "Label 4"]' data-data='[30,40]'></canvas>
As you can see, the charts can be of different types and I have an object holding all the configuration of charts for each type
const chartConfigs = {
bar: {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
pointRadius: 2,
backgroundColor: '',
maxBarThickness: 50
}]
},
options: {
legend: {
display: false
},
scales: barScalesOptions
}
},
pie: {
type: 'pie',
data: {
labels: [],
datasets: [{
data: [],
backgroundColor: ['#84c267', '#c9556a'],
borderWidth: 0
}],
},
options: {
legend: {
labels: {
fontColor: '#CCC',
}
},
aspectRatio: 1,
responsive: true
}
}
}
And I loop through all the canvases to initialize them.
container.querySelectorAll('canvas').forEach(canv => {
const chartOptions = chartConfigs[canv.dataset.type];
chartOptions.data.datasets[0].data = JSON.parse(canv.dataset.data);
if(canv.dataset.labels != undefined)
chartOptions.data.labels = JSON.parse(canv.dataset.labels);
console.log(JSON.stringify(chartOptions));
new Chart(canv, chartOptions);
});
But the problem is that all the charts are rendered the same - Labels and Data. I'm assuming its because chartOptions is a copy by reference. Its a pretty difficult task to do a deep copy as this is a nested object and I also need functions in them. But even if I somehow did this task, it would be a memory management nightmare as there are many charts on the page.
If you have done something like this before, please share a better way of doing this.
A quick solution is to clone the needed part of the object, with the handy function(s) JSON.parse and JSON.stringify, it makes sure it breaks all references (as mentioned on mdn).
container.querySelectorAll('canvas').forEach(canv => {
const chartOptions = JSON.parse(JSON.stringify(chartConfigs[canv.dataset.type]));
chartOptions.data.datasets[0].data = JSON.parse(canv.dataset.data);
if(canv.dataset.labels != undefined){
chartOptions.data.labels = JSON.parse(canv.dataset.labels);
console.log(JSON.stringify(chartOptions));
new Chart(canv, chartOptions);
});
Since I can't see any functions in the object chartOptions the serializing and deserializing should be no problem?
Update, for object with functions (for your specific case):
I see two easy options,
just extract the functions from the base object and just pass the current object
Or if you don't want to alter the chartConfigs object, just use the prototype function, call (link to documentation). With other words change the function calls to:
// clone
const chartOptions = JSON.parse(JSON.stringify(chartConfigs[canv.dataset.type]));
...
let id = 1;
let value = 100;
// call the function
chartConfigs[chartOptions.typ].testFunction.call(chartOptions, id, value);
...
(if testFunction would be a function, with 2 parameters ( id, value))
Is not very sexy, but is a fast solution, that will need little code modifications.

ApexChart: Line chart another option

Hi I am using АpexChart but I have problem setting up xaxis. The picture below is from another chart, but I'm looking for the effect it has. Note the long straight line, this means there is no data for the specific period.
How do I set up a АpexChart so I can display similar data
var options = {
series: [{
name: "Level",
data: [30,45,50,60,70,91,125]
}],
chart: {
height: 350,
type: 'line',
zoom: {
enabled: true
}
},
dataLabels: {
enabled: true
},
stroke: {
curve: 'straight'
},
title: {
text: 'Battery',
align: 'left'
},
grid: {
row: {
colors: ['#f3f3f3', 'transparent'], // takes an array which will be repeated on columns
opacity: 0.5
},
},
xaxis: {
categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999]
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
The chart we see on your screenshot has been made with Highcharts, right? I know that you can do something similar with amCharts or Chart.js. But this feature is not available in ApexCharts yet. With ApexCharts, you will get blanks (see demo) if you have null values in your data.
Take a look at this issue and this pull request on GitHub.
Comment of the library author (2019), from the issue:
This has been proposed, but not worked upon yet.
Comment of the library author (2021), from the PR:
Update: This PR doesn't solve the issue the way we wanted and doesn't cover multiple use-cases.
Please bear with us. There might be a new PR with a completely different implementation.

Chart.js - Mouseover causes graphs to flicker and resize

To start, I have made a short video to show exactly what I'm running into.
To summarize the video: while using Chart.js (2.6.0), I can create my charts without issue; but when I mouse-over the bars/points, the chart will resize its elements and flicker. The weird thing is that it's totally inconsistent. Sometimes when I refresh, it doesn't have this behaviour at all; but if I hover over something and it starts doing it, it won't stop until I refresh again or close out of the tab (it is inconsistent with this, also). I don't change anything in the code when this occurs, it does this all on its own.
In an attempt to fix it, I've referenced many other threads here on SO, as well as the Chart.js documentation. Among my solutions: I have made a point to add in a specified Height/Width to the Divs & Canvas creating the graphs; Set the Animation duration to 0, the Hover Animation duration to 0, and the Responsive Animation duration to 0; I've ensured that Responsive is set to true, and have kept Maintain Aspect Ratio as true, changed the tooltip mode... I've tried all of these, among other little things that seem to have little-to-no effect.
I'm stumped!
Here is one of my charts' code (without how I'm grabbing the JSON data etc, just the Chart):
new Chart($("#runwayChart"), {
type: "horizontalBar",
data: {
labels: runwayLabels,
datasets: [{
label: "Months Left", fill: true,
backgroundColor: "#3333ff",
borderColor: "#3333ff",
data: score
}, {
label: "Expenses",
fill: true,
backgroundColor: "#aa2222",
borderColor: "#aa2222",
data: expenses
}, {
label: "Revenue",
fill: true,
backgroundColor: "#2222aa",
borderColor: "#2222aa",
data: revenues
}]
},
options: {
tooltips: {
mode: 'index'
},
responsive: true,
maintainAspectRatio: true,
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0
}
});
I'd appreciate any help you all may have!
Thanks =)
I see that it has been a while since somebody wrote an answer to this post. I solved my flickering issue by applying two things.
First one
When I declare the chart I use:
var ctx = document.getElementById('chart').getContext('2d');
window.chart = new Chart(ctx, {}) ...
rather than var chart = new Chart(ctx, {})..
In this way, we make sure that the chart has been appended to the window. object.
Secondly
Before drawing the new diagram (For example for data update) we need to make sure that the previous canvas has been destroyed. And we can check that with the code below:
if(window.chart && window.chart !== null){
window.chart.destroy();
}
It was actually a really simple, and odd solution.
When the data point was near the top of the chart, the chart would try to resize depending on the div. As the chart lived in a larger canvas, putting inside its own div solved this issue.
<div>
<canvas id="chart"></canvas>
</div>
Formatting it like this was the solution =)
Try This :
var myLineChart = null;
function createChart() {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
myLineChart = new Chart(ctx1, {
type: 'horizontalBar',
data: {
labels: runwayLabels
, datasets: [{
label: "Months Left"
, fill: true
, backgroundColor : "#3333ff"
, borderColor: "#3333ff"
, data: score
}, {
label: "Expenses"
, fill: true
, backgroundColor : "#aa2222"
, borderColor: "#aa2222"
, data: expenses
}, {
label: "Revenue"
, fill: true
, backgroundColor : "#2222aa"
, borderColor: "#2222aa"
, data: revenues
}]
}
options:
{
scales: {
xAxes: [{
ticks: {
callback: function (tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';
}
return tick;
}
}
}]
},
tooltips: {
callbacks: {
// We'll edit the `title` string
title: function (tooltipItem) {
// `tooltipItem` is an object containing properties such as
// the dataset and the index of the current item
// Here, `this` is the char instance
// The following returns the full string
return this._data.labels[tooltipItem[0].index];
}
}
},
title:
{
display: true,
text: "Your Chart Title"
},
responsive: true,
maintainAspectRatio: true
}
});
}
I had the same issue with my angular application(angular v6 and chartjs 2.9.4).
After adding delay and destroying the chart instance before redrawing the chart resolved my issue.
public redraw() {
setTimeout(() => {
if (this.chart && this.chart != null) {
this.chart.destroy()
}
this.chart = new Chart(this.chartId, this.chartConfig);
}, 500);
}

Draw horizontal target line using EChart.JS

I would like to draw a horizontal target line showing threshold limits on a line, bar and pie chart using EChart.JS (https://ecomfe.github.io/echarts-doc/public/en/index.html).
There are other threads - "Chart.js - draw horizontal line" which detail how to do it with Chart.JS. Has anyone out there got particular experience on this with EChart?
Thanks in advance.
[Edit] Since Echarts v3 came up and was passed to the Apache Foundation, the documentation has been sclattered through different URLs, some options have gone away, some are not shown in all documentation resources, and so on. Links provided below have been updated (as of 24/02/2020) but might break again. I haven't fully tried v3 but provided code below should still work.[/Edit]
The option markLine is designed for that, see documentation here:
https://echarts.apache.org/en/option.html#series-line.markLine
Note that there are different uses for it, and different options to provide, depending on what you want to draw:
arbitrary line on the canvas (any size, any direction, any style)
lines matching data caracteristics (min, max, average)
horizontal/vertical lines
You have to use the attribute markLine.data in all cases, and description of specifics is described here:
https://echarts.apache.org/en/option.html#series-line.markLine.data
Here's how I go, with a line curve on a time serie. Note that I couldn't get, within markLine.data[0], yAxis to be enough to draw a horizontal line: xAxis must be specified too (start and end points).
xAxis: {
type: 'time',
},
yAxis: {
type: 'value'
},
series: [{
type: 'line',
xAxisIndex: 0,
yAxisIndex: 0,
data: [
[1509762600, 7.11376],
[1509832800, 7.54459],
[1509849000, 7.64559]
],
markLine: {
data: [
// 1st line we want to draw
[
// start point of the line
// we have to defined line attributes only here (not in the end point)
{
xAxis: 1509762600,
yAxis: 3,
symbol: 'none',
lineStyle: {
normal: {
color: "#00F"
}
},
label: {
normal: {
show: true,
position: 'end',
formatter: 'my label'
}
}
},
// end point of the line
{
xAxis: 1509849000,
yAxis: 3,
symbol: 'none'
}
]
]
}
}]
Here's a fiddle I found: https://jsfiddle.net/381510688/hff93ska/
Note that ECharts really like to display markLines with arrow symbols in the end of it, hence my use of symbol: 'none' in above code, to have just the line drawn.

HighCharts.js is not rendering chart under IE8

I am using HighCharts together with Python to dynamically create charts. All works fine, however I get cannot read property "0" of undefined exception under IE8. Unfortunetly my client want it to work under IE8 as well. So heres the code of the main function:
function generateChart(series) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'company_chart',
},
xAxis: {
type: "datetime",
},
yAxis: [{
title: {
text: "T1",
},
},{
title: {
text: "T2",
},
},
opposite: true,
}],
plotOptions: {
series: { shadow: false },
column: { shadow: false, },
},
series: series
});
);
Now my ajax request returns some data and I store it in the variable like this:
chart_data = [
{
type: "spline",
color: '#ff0000',
yAxis: 0,
data: dataT1,
},
{
type: "column",
color: '#0000ff',
yAxis: 1,
data: dataT2,
}
];
After that I call generateChart(chart_data);. The format of variables dataT1 and dataT2 is fine, since it works under every other browser. For example dataT1 may look like this:
dataT1 = [ [1325721600000,1.64],
[1325635200000,1.64],
[1325548800000,1.7],
[1325462400000,1.7],];
But still the exception is thrown under IE8. Any ideas how to fix this?
Those dangling commas are causing errors in Internet Explorer. Get rid of them.
Here's an example:
chart: {
renderTo: 'company_chart', // <--- get rid of that comma
},
Internet Explorer considers a comma at the end of an object literal like that to be an error. You should in fact be seeing the "Errors on page" warning, but the error is usually something that does not indicate this actual root cause.
edit — well apparently IE8 is not picky about that, though IE7 is.
edit again — However, IE8 interprets that last dangling comma in your data arrays as meaning that there should be an extra element! In other words:
[1, 2, 3,].length
is 3 in Firefox/Chrome/Safari but it's 4 in Internet Explorer. When you try to access that element, the browser gives you undefined.

Categories

Resources