[Chartjs]-Load Chart.js tooltip information asynchronously

1👍

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);
}

Leave a comment