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.
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.:and then access them in the hook:
If
labelsandparentshave to be updated frequently, you should consider pushing the data (usingpush_event) from the server and define ahandleEventfunction on the client.See also the Phoenix documentation for hooks and client-server-documentation.