Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Chart.js tooltip information asynchronously

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?

like image 833
Saber Avatar asked Nov 07 '22 11:11

Saber


1 Answers

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);
}
like image 62
Olexandr Avatar answered Nov 12 '22 16:11

Olexandr