albertosh

albertosh

Calling a js file from Phoenix Live View

I have a Live view that renders a

and injects a script file for that page. The script contains a function that renders a chart on the div based on the data provided to the div via a data attribute. It all works great the first time, but when I change one filter, the live view gets re-rendered and now the chart is all white (no chart rendered). I’m pretty new to Phoenix so I might be doing something wrong, but just in case, I’ll leave some code here.

/views/cash_flow_view.ex

defmodule Proj.CashflowView do
  use ProjWeb, :view

  def date_group_filters() do
    [
      "By Month": :by_month,
      "By Quarter": :by_quarter,
      "By Year": :by_year
    ]
  end

  def render("scripts.html", _assigns) do
    ~E(<script src="./js/charts.js"></script>)
  end
end

live/cashflow_live_view.ex

defmodule ProjWeb.CashflowLiveView do
  use Phoenix.LiveView
  alias Poison

  alias ProjWeb.CashflowView
  alias Proj.Cashflow
  
  def render(assigns) do
    IO.inspect "RENDERING AGAIN"
    IO.inspect assigns.cashflow

    ~L"""
    <h3>Cash flow</h3>
    <%= CashflowView.render("filters.html", assigns: assigns) %>
    <div id="chart" data-cashflow="<%= Poison.encode!(assigns.cashflow) %>"></div>
    <%= CashflowView.render("scripts.html", assigns: assigns); %>
    """
  end

  def mount(session, socket) do
    {:ok, assign(socket, session)}
  end

  def handle_event("update_filters", %{"filters" => filters}, socket) do
    cashflow = case Map.get(filters, "date_group") do
      "by_month" ->
        Cashflow.cashflow_by_month(socket.assigns.user_id)
      "by_quarter" ->
        Cashflow.cashflow_by_quarter(socket.assigns.user_id)
      "by_year" ->
        Cashflow.cashflow_by_year(socket.assigns.user_id)
    end

    {:noreply, assign(socket, cashflow: cashflow)}
  end
end

/scr/chart.js

import Taucharts from "taucharts";
import tooltip from "taucharts/dist/plugins/tooltip"

export var Chart = { 
  render: function() {
    const chartDiv = document.querySelector('#chart');
    const data = JSON.parse(chartDiv.dataset.cashflow);

    const chart = new Taucharts.Chart({
      data: data,
      type: 'line',
      x: 'date',
      y: 'amount',
      color: 'type',
      guide: {
        x: {label: {text: 'Month', padding: 35}, padding: 20},
        y: {label: 'Cashflow', padding: 20},
        padding: {b: 70, l: 70, t: 10, r: 10},
        showGridLines: 'y'
      },
      plugins: [
        tooltip()
      ]
    });

    chart.renderTo('#chart');    
  }
}

setTimeout(() => Chart.render(), 1000)

My 2 questions would be:

  1. Is there a way to avoid having to use that setTimeout? If I don’t use it then the chart probably never gets rendered.
  2. How can I make sure that inside the live view I can get access to chart? and call it’s methods from there?

Thanks!

Most Liked

rhcarvalho

rhcarvalho

Very late to the party, but since this got many views already, I’ll leave a reference for those landing here in the future – myself included.

I used to embed some arbitrary JS code like the OP into a LiveView, also with some side effects. Works apparently okay on the first render, but doesn’t work if live navigating back to the page.

I think the solution is as @LostKobrakai said in Re-render JS on a Live view update - how to? - #2 by LostKobrakai, either using JS events or hooks:

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
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
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 49084 226
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 42533 114
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement