Send event from live component to parent Live View

I have a parent Live View with a live component that does a thing within itself. One of the results of this thing could be an error and if that is the case I would like to send an event or otherwise get that info to the parent live view so that I can put_flash an error message. What, if any, are the options for doing this? Thanks!

Basically one idiomatic option: send(self(), :your_thing) and handle_info in parent LV.

5 Likes

Awesome, thanks! Worked just like I wanted.

The solution works fine in the browser. But I tried to test it (actually my already existing tests are now failing). I extracted a part of my live view into a stateful component.

In my component i use send/2 to notify the parent live view to react. That is basically showing a flash message. That works just fine in the browser.

def handle_event("save-admin", params, socket) do
  send(self(), {:save_admin, params})

  {:noreply, socket}
end
{:ok, index_live, _html} = live(conn, Routes.settings_index_path(conn, :index))
rendered =
  index_live
  |> form("my-form-id")
  |> render_submit()

# it fails here!
assert rendered =~ "Admin updated successfully"

I fear it fails because the test is too quick to get the update from the parent view. Any idea how to test that properly?

:timer.sleep(3000) ?

No that does not help. But re-rendering helped, see [LiveTest] LiveView render doesn't happen if the event is handled by included LiveComponent.