Pass custom/render-time data to LiveView client side hook

Although you found a kind of solution I’d like to add what I am doing when I need custom data in a hook.

There are two approaches which I found useful.

Use a data attribute and fetch it from the hook mount callback.

const Foo = {
  getBar() {
    // on string data
    return this.el.dataset.bar;
    
    // when using JSON data
    return this.el.dataset.bar && JSON.parse(this.el.dataset.bar);
  },
  mounted() {
    console.log('data from bar:', this.getBar());
  },
};
<.button phx-hook="Foo" data-foo="hello">Click Me</.button>
<.button phx-hook="Foo" data-foo={Jason.encode!(%{ bar: "world"})}>Click Me</.button>

I use that approach all the time if I want to process some data and the data is cheap to render inside the template.

Use pushEvent to send an init message and get the data via the reply.

const Foo = {
  mounted() {
    this.pushEvent('Foo:init', {}, (reply) => {
      if (reply.foo) {
        console.log("Got data for foo", reply.foo);
      }
    });
  },
};

In your LiveView:

<.button phx-hook="Foo">Click Me</.button>

def handle_event("Foo:init", _params, socket) do
  {:reply, %{foo: "bar"}, socket}
end

This approach is more suitable if you need to perform more complex tasks or have big payloads. For example I use this to initialize a rich text editor with a state stored in the db.