Is there a way to pass initial values to a LiveView JS hook from the server?
Here’s my example LiveView:
defmodule FooWeb.PageLive do
use FooWeb, :live_view
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, foo_assigns_i_want_to_reference_in_my_hook: %{bar: "hi"})}
end
@impl true
def render(assigns) do
~L"""
<div phx-hook="FooDomNode"></div>
"""
end
end
And here is my JS hook:
let Hook = {}
Hook.FooDomNode = {
mounted() {
// Is there anyway I can access `foo_assigns_i_want_to_reference_in_my_hook` in here?
}
}
// ... More JS boilerplate that properly passes `Hook` to `new LiveSocket(...)` and connects
As the commented part of the JS hook states: Is there anyway to reference the assigns of the LiveView mount in the JS hook’s mounted callback?
I’m going to preemptively add: I’m wondering if there is a cleaner and more official way to do this than to serialize the assigns in a data attribute on the hook’s node.
There are a few ways of communicating back and forth. The aforementioned push_event, the aforementioned assigning to a data attribute and reading it, e.g.
You see the data-value attribute in the render function is picked up in the value() function on the hook. data-value in the Hook’s tag is picked up by this.el.dataset.value.
See Phoenix LiveDashboard chart code which does this.
You can then send things back to the server with pushEvent and pushEventTo if you need.
Something like this:
// listen to event: color changed in picker
// this.picker.addEventListener("change", (e) => {
// this.pushEventTo(this.el.dataset.target, "set_color", {
// id: this.el.getAttribute("id"),
// color: e.value,
// });
// });