Skip to content

phx-hook on root node in LiveComponents causes runtime error when using this.pushEventTo #4088

@krilllind

Description

@krilllind

Environment

  • Elixir version (please paste the output of elixir -v):
Elixir 1.19.4
  • Phoenix and LiveView versions (mix deps | grep -w 'phoenix\|phoenix_live_view'):
* phoenix 1.7.21 (Hex package) (mix)
  locked at 1.7.21 (phoenix) 336dce4f
* phoenix_live_view 1.1.18 (Hex package) (mix)
  locked at 1.1.18 (phoenix_live_view) f189b759
  • Operating system:
  • Windows
  • MacOS
  • Linux
  • Other (please specify):
  • Browsers (including version) you attempted to reproduce this bug on (the more the merrier):
Arc Version 1.125.1 (72271)
Chromium Engine Version 143.0.7499.110

Actual behavior

If you render a LiveComponent and apply the phx-hook attribute to the root element, the using the this.pushEventTo(this.el, ...) function causes a runtime exception on the targetContainer being null.

Example:

// live_component.ex

def render(assigns) do
~H"""
<div id={@id} phx-hook="MyHook">
  ...
</div>
"""
end

```ts
// myHook.ts
export class MyHook extends ViewHook {
  public mounted() {
    document.addEventListener("some_event", () => {
      this.pushEventTo(this.el, "my_update", {}); // <- This yields runtime errors
    });
  }
}

Expected behavior

I get that a phx-hook should probably not be applied on the root node of a LiveComponent, but it also sort of works at times. Maybe we could log a warning if hook is placed on the wrong element? Alternatively add something to the docs?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions