polypush135
Using LivieView with chart.js whats it like to feed data to a js lib?
I wanted to start a convo around how to render templates that define js data feeding data into a lib like chart.js via LiveView. When reviewing chart.js docs on how it want’s its data Data structures | Chart.js I realize I have a disconnect
Have any of you tried this yet? What’s your experience been?
Getting alpine to work in liveview was easy enough but how do define the datasets via the LiveView templates has me scratching my head.
Marked As Solved
benwilson512
We do this with Phoenix.LiveView — Phoenix LiveView v1.2.5. The chart is defined in a hook, and then we use push_event to push data to the hook. Works great, and makes it easy to support chart.js or any number of other chart libraries.
Also Liked
APB9785
If you want to give some data to initialize the chart, you can assign it:
def mount(_params, _session, socket) do
{
:ok,
assign(socket,
temp_chart_data: %{
labels: ["foo", "bar"],
values: [21, 12]
}
)
}
end
Then pass it to your chart as data-whatever-you-like in the render/html.leex
<canvas id="temp-chart-canvas"
phx-hook="TempChart"
data-chart-data="<%= Jason.encode!(@temp_chart_data) %>">
and then you can use dataset.whateverYouLike in your hook to initialize the chart:
Hooks.TempChart = {
mounted() {
const { labels, values } = JSON.parse(this.el.dataset.chartData)
this.chart = new TempChart(this.el, labels, values)
...
handleEvent...
benwilson512
The issue is that you have a race condition. handle_params is run before the javascript on the page has fully rendered. Instead of pushing it in handle_params, instead have the hook JS, on mount, push a “get me the data” event to the live view, which you do in a handle_event clause. Then in that, you send the data.








