Event from hook is sent to parent instead of component

i am having an issue where i am attempting to push an event from a JS hook to a component. it is a live component, and i can see it is using the correct target, however i am getting a

** (FunctionClauseError) no function clause matching in ScorpionWeb.ActivityLive.handle_event/3
    (scorpion 0.1.0) lib/scorpion_web/live/activity/activity_live.ex:38: ScorpionWeb.ActivityLive.handle_event("toggle_show_more", %{"id" => "excluded", "target" => "2"}

where ActivityLive is the parent live view.

i tried pattern matching on what i was getting back in the error, but it still wants the event to come from the parent live view. the event does, however, work from the live component when i put the phx-click event and a phx-target on the button. so it seems to be an issue when propagating the event from the js hook.

here is my live component event

  def handle_event("toggle_show_more", %{"id" => section_id, "target" => _}, socket) do
    show_more = Map.get(socket.assigns.show_more, section_id, false)
    updated_show_more = Map.put(socket.assigns.show_more, section_id, !show_more)

    {:noreply, assign(socket, show_more: updated_show_more)}
  end

and my component

<div phx-hook="CheckHeight" id={@id} class="relative" data-target={@target}>
        <.link class="button text-sm text-teal-600 dark:text-teal-400 underline z-10 relative">
          <%= gettext("Show More") %>
        </.link>
</div>

and my js

Hooks.CheckHeight = {
  mounted () {
    const container = this.el
    const button = container.querySelector(':scope .button')

    button.addEventListener('click', () => {
      const sectionId = this.el.getAttribute('id')
      const target = this.el.getAttribute('data-target')
      console.log(target)
      this.pushEvent('toggle_show_more', { id: sectionId, target: target })
    })
  }
}

again, i have confirmed it’s passing the right target. any further questions or help are appreciated, thank you!

You want to use pushEventTo in order to target the live component

this.pushEventTo(`#section-${target}`, 'toggle_show_more', { id: sectionId, target: target })

Run in Livebook

2 Likes

amazing, that worked, thanks!!!