alvises

alvises

Realtime JS chart in LiveView with hooks - what do you think?

I’ve started experimenting with JS charts in LiveView and update the chart with realtime data using LV hooks. I’m able to add new datapoints to the chart without having to redraw it everytime. It seems to work well, BUT I’m not convinced if in this way, in case of really fast updates. the chart can suffer of data loss.

liveview_chart

I’m using Highstock

app.html.eex

<!DOCTYPE html>
<html lang="en">
  <body>
    ...
    <script src="https://code.highcharts.com/stock/highstock.js"></script>
  </body>
</html>

chart_live.ex

defmodule ChartWeb.ChartLive do
  use Phoenix.LiveView

  def mount(_session, socket) do
    :timer.send_interval(1_000, self(), :next_price)
    socket =
      socket
      |> assign(:prices, historical())
    {:ok, socket}
  end

  def render(assigns) do

    ~L"""
    <div phx-hook="Chart" data-prices="<%= @prices %>"></div>
    <div phx-update="ignore">
      <div id="chart" style="width:100%; height:400px;" ></div>
    </div>
    <pre><%= @prices %></pre>
    """ |> IO.inspect()
  end

  def handle_info(:next_price, socket) do
    now_unix = DateTime.utc_now |> DateTime.to_unix(:second)
    {:noreply, assign(socket, :prices, Jason.encode!(random_data(now_unix)))}
  end

  # creates last 10 minutes of random data
  def historical() do
    now_unix = DateTime.utc_now |> DateTime.to_unix(:second)
    hour_ago_unix = now_unix - 60*10

    hour_ago_unix..now_unix
    |> Enum.map(&random_data(&1))
    |> Jason.encode!()
  end

  def random_data(unix_seconds) do
    [unix_seconds * 1_000, Enum.random(100..200)]
  end
end

app.js

Hooks.Chart = {
    lastprice() { return JSON.parse(this.el.dataset.prices)},
    createChart(data) {
        return Highcharts.stockChart('chart', {
            title: {
                text: 'Random prices with Phoenix LiveView'
            },
            series: [{
                name: 'A stock',
                data: data
            }]
        });
    },
    addPointToChart(chart, price) {
        chart.series[0].addPoint(price, true, false)
    },
    mounted() {
        console.log("Chart LiveView mounted");
        
        //using data-historical (last hour of random data)
        let historical = JSON.parse(this.el.dataset.prices);        
        this.chart = this.createChart(historical);
    },
    
    updated() {
        let price = this.lastprice();
        console.log(price)
        this.addPointToChart(this.chart, price)
    }
}

mount and initialization

The ChartLive module initially renders all the historical prices into data-prices attribute (`socket.connected? case to be handled, to avoid to send the whole historical data two times)

When the view is mounted, the mounted function in the JS hooks is called, it reads the data from the data-prices attribute and it creates the chart with that historical data.

Updates

Then for each new price sent from LV, the data-prices is patched and for each update Hooks.Chart.updated() function is called. It takes the new prices from the data-prices attribute and it adds it to the chart.

Considerations

I think that this approach reduces the data hold, rendered and transmitted to the minimum (without taking a huge list of prices into memory and redrawing the whole chart every time) …

BUT, I honestly don’t know how it works in case of rapid updates: is it possible that the JS LiveView on the client side patches the DOM with new data, before update() is able to grab and add the last price to the chart?

Most Liked

chrismccord

chrismccord

Creator of Phoenix

Confirm this is exactly what we do on the LiveDashboard and it’s a great approach. Provided your chart update code is synchronous, then it guaranteed to not have any races as everything will happen in the same event loop.

10
Post #5
alvises

alvises

Sorry, the image’s link has expired. Here’s the result,

And here with a point every 50ms

I’m still investigating if there could be a race condition in updated():sweat_smile:

alvises

alvises

Looking at the new Phoenix 1.5-rc0, the LiveDashboard seems to use a similar method

https://github.com/phoenixframework/phoenix_live_dashboard/blob/master/lib/phoenix/live_dashboard/live/chart_component.ex#L34

Where Next?

Popular in Discussions Top

vans163
So useless benchmarks aside, Its possible to write a webserver that can serve 300k requests per second (perhaps more with optimizations)....
New
ricklove
I was just introduced to Elixir and Phoenix. I was told about the 2 million websocket test that was done 2 years ago. From my research, t...
New
Ankhers
Just a little information upfront. Generally speaking, if I feel like I need to either break a pipe chain or use an anonymous function in...
New
lorenzo
Hey everone! I created a prototype for my app using Nodejs for the api. But the framework I chose wasnt great (in general theresnt any g...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54250 245
New
MarioFlach
Hello, I want to share a project I’ve been working on for a while: https://github.com/almightycouch/gitgud Background Some time ago I ...
New
axelson
Decided against including more info in the title, but the gist is that Plataformatec sponsored projects will continue with the assets bei...
New
sashaafm
Piggy backing a bit on @dvcrn topic BEAM optimization for functions with static return type?, I’ve been trying to understand in a deeper ...
New
AstonJ
It’s been a while since we’ve had a thread like this, so what better way to kick off the year with :003: What does being an Elixir user ...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New

We're in Beta

About us Mission Statement