I know that we can load the information for the tooltip of a chart by using the code below:
window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return tooltipItems.yLabel + ' €';
}
}
},
}
});
The problem is that in my case I need to call a function and return the values asynchronously; possibly show a spinner till the response is ready. How can I accomplish this?
You may to call chart.js update() method asynchronously instead. You may want to use a recursion also if the label should depend on which data point hovered by user.
window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: asyncTooltipLabel
}
},
}
});
function asyncTooltipLabel(tooltipItems, data) {
// some asynchronous function call
setTimeout(function() {
// when asyncronous result comes
const result = (tooltipItems[0].index * 2) + ' €';
const newTooltipConfig = {
enabled: true,
mode: 'single',
callbacks: {
label: function(newTooltipItems, newData) {
if (newTooltipItems[0].index === tooltipItems[0].index && newTooltipItems[0].datasetIndex === tooltipItems[0].datasetIndex) return result;
else asyncTooltipLabel(newTooltipItems, newData);
}
}
}
// apply new tooltip config
window.myLine.options.tooltips = newTooltipConfig;
window.myLine.update();
}, 2000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With