imacrayon / alpine-ajax

An Alpine.js plugin for building server-powered frontends.
https://alpine-ajax.js.org
MIT License
561 stars 12 forks source link

Example using ChartJS #13

Closed Art9681 closed 1 year ago

Art9681 commented 1 year ago

I have been trying to get ChartJS integration working to display host metrics using AJAX requests. However, I have not been able to find examples with this use case. Assume we make an API call that returns JSON data displaying CPU metrics in the following format when making a get request to /nodecpustats:

"KernelSet":true,"Kernel":501435,"UserSet":true,"User":443484,"IdleSet":true,"Idle":112996834,"IowaitSet":true,"Iowait":5197,"IntrSet":true,"Intr":0,"UtilizationSet":true,"Utilization":95011600}

How can we display the Utilization metric as time series data using Alpine+ChartJS? How can we make the chart reactive and smooth scroll? Any help would be appreciated.

imacrayon commented 1 year ago

Alpine AJAX is intended to work with APIs that return HTML not JSON, so if /nodecpustats is a third-party data source that you don't control, you might be better off using plain Alpine with the fetch call in your client-side code like this:

<canvas x-init="new Chart(this.$el, {
  type: 'line',
  data: {
    datasets: [{
      data: fetch('/nodecpustats'),
    }]
  }
})"></canvas>

However, if /nodecpustats is an endpoint you've built, it might be simpler to re-work that endpoint to return the HTML that includes your chart data server-side like this:

<canvas id="my-chart" x-init="new Chart(this.$el, {
  type: 'line',
  data: {
    datasets: [{
      data: [{"Idle":112996834,"IowaitSet":true,"Iowait":5197,"IntrSet":true,"Intr":0,"UtilizationSet":..}...]
  }
})"></canvas>

Then you could use Alpine AJAX somewhere on the page to issue different requests that would instruct the server to update the chart data:

<div x-ajax>
<a x-target="my-chart" href="/nodecpustats?cpu=3">Show CPU 3 data</a>
<a x-target="my-chart" href="/nodecpustats?cpu=4">Show CPU 4 data</a>
</div>

let me know if that all makes sense 🙂

Art9681 commented 1 year ago

Thank you for the help with this. It makes perfect sense. Previously I was using htmx to return the chart but I refactored to Alpine thinking the data could be "streamed" to the chart and it would be cleaner. Looks like a similar solution needs to be employed here. I appreciate it and great work on the add-on.