Fetch data for Chart.js tooltips dynamically

One common way to load information for a tooltip in a chart is by using the following code snippet:

window.myLine = new Chart(chart, {
  type: 'line',
  data: lineChartData,
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: function(tooltipItems, data) {
          return tooltipItems.yLabel + ' €';
        }
      }
    },
  }
});

However, I faced an issue where I needed to retrieve values asynchronously by calling a function and show a loading spinner until the response is ready. How can I achieve this dynamic behavior?

Answer №1

To update chart.js asynchronously, consider using the update() method. You can also implement recursion if the label needs to change based on the data point hovered by the user.

window.myLine = new Chart(chart, {
  type: 'line',
  data: lineChartData,
  options: {
    tooltips: {
      enabled: true,
      mode: 'single',
      callbacks: {
        label: asyncTooltipLabel
      }
    },
  }
});

function asyncTooltipLabel(tooltipItems, data) {
  // Perform some asynchronous operation
  setTimeout(function() {
    // Handle asynchronous result
    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);
           }
       }
    }

    // Update tooltip configuration
    window.myLine.options.tooltips = newTooltipConfig;
    window.myLine.update();
  }, 2000);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving the 'node-gyp rebuild' problem on Windows 10

While attempting to incorporate a node NPM dependency into my project, I encountered an issue with node-gyp rebuild, which I have already reported. I am aware of a potential solution from this Stack Overflow post, but unfortunately it is not effective for ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Activate ajax search in select2 by hand

I recently integrated the select2 plugin with jQuery into my website. For the most part, it functions perfectly. One particular feature I have is a search widget that utilizes select2 and remote data search. When I enter a search query using a keyboard ...

Encountering an issue in my Next.js application with the app router where I am unable to read properties of undefined, specifically in relation to '

As I develop a basic Rest API in Next.js, my goal is to display "Hello world" in the console for a post api. export const POST = (req: Request) => { console.log('hello world'); }; The error message that appears in my terminal is as follows: ...

What could be causing the error message "CSRF token missing or incorrect" to appear?

I am facing an issue with returning a value from a View function in Django. This particular function is called from a JavaScript code using Ajax, but I'm encountering an error that says 'Forbidden (CSRF token missing or incorrect)'. JavaScr ...

What is the proper way to connect my JavaScript code to my HTML form?

My JavaScript function is not working properly when I try to submit a form on my website. <form onsubmit="validateRegistration()"> <p> // Email registration <input type="text" id="e-mail" placeholder="Email" /> </p> ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

Encountering difficulties while trying to include js-search in a Vue.js component

My current challenge involves importing the js-search npm module into a Vue component. However, whenever I attempt to do so using: import JsSearch from 'js-search' The subsequent console.log(JsSearch) statement returns undefined. To further in ...

Building a solid foundation for your project with Node.js and RESTful

I need to integrate a legacy system that offers an api with rest/json queries in Delphi. I plan to consume this data and build an app using angular + nodejs. My goal is for my application (client) to only communicate with my web-server on nodejs, which wil ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

What could be the reason for the lack of read or write functionality in $cookies for angular version 1.6.6?

I am relatively new to working with Angular. I have started a test project and my goal is to store user authentication in cookies. Despite my best efforts, I keep encountering an undefined error when attempting to retrieve the stored value. I am not sure w ...

Retrieve all the records from the collection that have a specific reference number in their ID field

Is it feasible to pull together all documents with an ID that includes a specific value? I am working with Angular 7. I attempted using db.collection('items').where.. but unfortunately, this method is not supported. For instance: (collection) ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in t ...

Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "" ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

Tracking dynamic collections in AngularJS ng-repeat using track by

I am attempting to utilize ng-repeat with the result of a function call, like this: <body ng-init='a = [1, 2, 3]'> <div ng-repeat='item in f(a) track by item[0]'>{{item}}</div> </body> where the function f is ...

Utilizing a linked list to manage consecutive JS/Ajax/Jquery requests for seamless processing

Here is my code snippet: <script type="text/javascript"> var x = 1; var data = JSON.parse( document.getElementById('json').innerHTML); var next = data['next']; var jsonData = data['data']; ...