When using a JS hook, how do we send data to/from Ecto?

When using a JS hook, how do we send data to/from Ecto?

I am trying to integrate a library named Ploty.js into a LiveView app. Plotly.js is a graphics library and it requires a parent DOM node to attach itself to. I created a JS Hook in Phoenix and it works.

My hook:

import Plotly from "../vendor/plotly"
let liveSocket = new LiveSocket("/live", Socket, {

	params: {_csrf_token: csrfToken},


                      let element = document.createElement("DIV");
                      element.id = "test";
                       Plotly.newPlot("test", [{
    			      type: "treemap",
    			      labels: ["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
    			      parents: ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ]



Pltly.js renders to a single DOM node in a LiveView:

<div id="myPlot" phx-hook="myPlot">
  <!-- Plotly chart will be drawn inside this DIV -->

I want to move data to and from Ecto so that I can render the result in the graphics library. I am unsure what Phoenix tools are available for this, or where to focus my attention. It looks like I could do with with a fetch and hit an existing route that behaves as a data API but I am still curious about this.

Thank you

Client-server communication

A hook can push events to the LiveView by using the pushEvent function and receive a reply from the server via a {:reply, map, socket} return value. The reply payload will be passed to the optional pushEvent response callback.

source: JavaScript interoperability — Phoenix LiveView v0.18.18

To expand on what @codeanpeace says, you would have the javascript talk to the liveview. There are basically 2 work flows:

Getting the data

  1. push an event to the liveview asking for data
  2. Liveview uses ecto to fetch the data from the DB
  3. Liveview pushes the response to the js

Writing data

  1. push an event to the liveview with new data
  2. Liveview uses ecto to write the data to the db
1 Like