Send event to CID

I have a hierarchy of a few live_components. I need to allow one liveview to send an event to its caller progromatically. (like, I only want to send it once they hit the “enter” key on a selection)

defmodule Parent do
  use AppWeb, :live_component
  
  def render(assigns) do
    ~F"""
    <Child id="search-select1" did_select="did_select" />
    """
  end

  def handle_event("did_select", value, socket) do
    IO.inspect(value)
    {:noreply, socket}
  end
end

defmodule Child do
  use AppWeb, :live_component

  prop did_select, :event, required: true

  def render(assigns) do
    ~F"""
    <div class="flex flex-col">
      <TextField type="search" keyup="update_search" />
    </div>
    """
  end

  def handle_event("update_search", %{"key" => "Enter"}, socket) do
    # ????? How do I send trigger `did_select` event here???
    {:noreply, socket}
  end
end

I see that target is a %Phoenix.LiveComponent.CID{cid: 5}. So how can I send an event programmatically to %Phoenix.LiveComponent.CID{cid: 5}?

The cid cannot be used, but you can do send_update(MyComponent, id: 123, ..), so have your sender keep the component module/id as a tuple it its state and send that way.

2 Likes