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

mikl
I wanted to capitalize a string, and tried using String.capitalize(). That generally works well, until you try to capitalize a word like...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New
nunobernardes99
Hi there Elixir friends :vulcan_salute: In a recent task I was on, I needed to check in two dates which of them is the maximum and which...
New
AlexMcConnell
The reason that Rails is as popular as it is is because it’s very easy for relatively inexperienced developers to get a lot of work done....
588 19675 166
New
mbenatti
Following https://github.com/tbrand/which_is_the_fastest |&gt; https://raw.githubusercontent.com/tbrand/which_is_the_fastest/master/imgs...
New
jer
I’ve been using umbrellas for a while, and generally started off (on greenfield projects at least) by isolating subapps based on clearly ...
New
hazardfn
I suppose this question is effectively hackney vs. ibrowse but we are at a point in our project where we have to make a choice between th...
New
acrolink
How does the two languages compare when it comes to server side application development? Any experiences or ideas? Thank you.
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New

Other popular topics Top

ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
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
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement