0

In Phoenix, I am using a third-party library named Plotly.js. To incorporate it, I am using a JavaScript Hook.

How can I get data from Ecto to Plotly via the JS Hook?

To crystalize my problem I have a tangible example below.

let liveSocket = new LiveSocket("/live", Socket, {

params: {_csrf_token: csrfToken},
hooks:{
    myPlot:{
        mounted(){
              let element = document.createElement("DIV");
              element.id = "test";
              this.el.appendChild(element)
              Plotly.newPlot("test", [{
              type: "treemap",
              labels: ["Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
              parents: ["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ]
           }])
        }
    }
}
})

I want to abstract the labels and parents data into a database. How would I retrieve the data if I needed to capture it from a database? I could create a new route that acts as a data API specifically for this purpose, but I figure there might be an easier way that I don't know about.

Syed M. Sannan
  • 1,061
  • 2
  • 9
  • 28
William
  • 4,422
  • 17
  • 55
  • 108

1 Answers1

0

Writing and reading the labels and parents from a database should be done in the server code of your application. These can then be read from e.g. the LiveView process.

Then in your template (or render function), in which you have the element with the hook attached, you can set multiple data- attributes (with values in the LiveView assigns), e.g.:

 <div
  id="unique-id"
  phx-hook="myPlot"
  data-labels=@labels
  data-parents=@parents
  ...
>...</div>

and then access them in the hook:

hooks:{
  myPlot:{
    mounted(){
      ...
      let labels = this.el.dataset.labels;
      let parents = this.el.dataset.parents;
      ...
    }
  }
}

If labels and parents have to be updated frequently, you should consider pushing the data (using push_event) from the server and define a handleEvent function on the client.

See also the Phoenix documentation for hooks and client-server-documentation.

jakobfp
  • 83
  • 7