thank you for reading. I'm trying to update by doughnut chart (from Char.js). Following is part of my html code. [Html]
<div >
<canvas id="doughnutChart" height="250%"></canvas>
<div >
<span ></span>%
</div>
<button id="">Click ME</button>
<span id="indexProduced"></span>
</div>
Following is parts of my js code
const getDataFromSheet = async () => {
try {
const res = await axios.get('https://sheetdb.io/api/v1/pr969olea08op')
return res.data;
}
catch (e) {
console.log('error', e)
}
}
const produced = document.querySelector('.indexProduced');
const indexButton = document.querySelector('.indexButton');
const getProduced = async () => {
const PRO = await getDataFromSheet();
console.log(PRO[0].Val);
produced.innerText = Number(PRO[0].Val)
}
indexButton.addEventListener('click', getProduced);
var indexData = [Number(document.querySelector('.indexProduced').innerText), 720];
const chart1 = document.getElementById("doughnutChart");
const myChart = new Chart(chart1, {
type: 'doughnut',
data: {
labels: ["발전량", "총 소모량"],
datasets: [
{
label: "Population (millions)",
backgroundColor: ["rgb(58, 149, 231)", "rgba(58, 149, 231, 0.2"],
data: indexData
}
]
},
});
So what I'm trying to do is
- Get Data from the API, display(update) it on html everytime I click the button.
- Using the displayed data, get it with 'QuerySelect', use it as data for chart
Getting the data from API is succesful, also displaying it is. But the problem is that the chart is not updating and shows the initial value.
The reason I'm doing this way is because I know no any other ways. If there is better ways for getting data from API above and update it as Chart, it would be super nice if I could know. Thanks for reading!
CodePudding user response:
I actually do not clearly understand the issue but once I faced the issue that I have to update the graph data every time when the button is clicked by the user. So for that, I just normally get the data from API and just put it on my graph js but sometimes it shows and sometimes it is not showing then I fixed that issue by removing the graph div and again appending it and reinitializing the graph once the button is clicked. I don't that if it fixed your issue or not but in my case it runs perfectly. I'll some sample code of my work Here is my HTML code:
<div id="topModelGraph" >
<canvas id="top-model"></canvas>
</div>
This is my js Code:
$('div#topModelGraph').empty();
$('div#topModelGraph').append('<canvas id="top-model"></canvas>');
var ctx = document.getElementById('top-model');
var lineChart = new Chart(ctx, config);
CodePudding user response:
It seems in the code you are not invoking myChart.update()
method which will update and re-render the chart, after you click the button.