hook's handleEvent event not working

Context: I have a game that is client rendered via a live view with a custom hook. I am looking to persist a value to local storage so that the client side can re-hydrate its state on reconnect or refresh.

My live view gets set up via handle_params/3 and looks like

def handle_params(%{"id" => id, "name" => name}, _url, socket) do
  case Games.get_active_room(id) do
    nil ->
      socket
      |> put_flash(:error, "Game room #{id} not found")
      |> push_navigate(to: "/")
      |> then(fn socket -> {:noreply, socket} end)

    %Room{} = room ->
      Endpoint.subscribe(@current_game <> id)
      Presence.track(self(), @current_game <> id, name, %{name: name})
      Presence.track(self(), @all_players, "game_" <> id <> "_" <> name, %{name: name})
      broadcast_readiness(@current_game <> id, game_ready?(id, room.num_players))

      socket
      |> push_event("set_game_id", %{id: nil})
      |> assign(name: name)
      |> assign(room_id: id)
      |> assign(messages: %{})
      |> assign(game_ready: false)
      |> assign(winner: "")
      |> assign_async(:answer, fn -> get_answer(id) end)
      |> then(fn socket -> {:noreply, socket} end)
  end
end

In the hook’s mounted callback, I have the following listener (which does not work):

this.handleEvent("set_game_id", function (game) {
  console.log("set_game_id called");
  console.log({ game });
});

However, after doing a little debugging, I realized that registering an event listener on the window does work:

window.addEventListener("phx:set_game_id", (e) => console.log(e));

Is there something I am missing with regards to getting this to work in the hook?

That sort of thing does work. I usually only push events in the connected mount/handle_params though. You could try if connected?(socket), do: push_event(...)

Thanks, I may try that just to learn. I ended up just changing the implementation to pass these as attributes on the element via assigns, which feels much simpler for the use case.