0

In a live view I have this snippet:

  <div id="chat"><%= live_render(@socket, MyAppWeb.ChatLive.Index, id: "watch-chats", guest: @guest) %></div>

In ChatLive.Index I have this mount function:


  @impl true
  def mount(%{"guest_id" => guest_id}, _session, socket) do
    ...
  end

  def mount(:not_mounted_at_router, session, socket) do
    mount(%{"guest_id" => socket.assigns.guest.id}, session, socket)
  end

but it gives this error:

key :guest not found in: %{flash: %{}, live_action: nil}

at the line with mount(%{"guest_id" => socket.assigns.guest.id}, session, socket).

How can I pass in a parameter such as guest to the live_render call and pick it up within the mount function?

ijt
  • 3,505
  • 1
  • 29
  • 40

2 Answers2

0

If you need to pass data, you would need to put it in the assigns of the socket.

franckstifler
  • 396
  • 2
  • 11
-1

You need to connect what you're passing into the live_render as params in the mount and then assign them to the socket if you need them available later.

Like this:

  <div id="chat"><%= live_render(@socket, MyAppWeb.ChatLive.Index, id: "watch-chats", guest: @guest) %></div>

And then this:

  def mount(%{"id" => id, "guest" => guest}, _session, socket) do
    ...
    new_socket = 
      socket
      |> assign(:id, id)
      |> assign(:guest, guest)
    {:ok, new_socket}
  end

Then those values should be available to pull from your socket object where ever it is.

But you could also store other values. If you only wanted to keep the guest_id and not the whole struct you could do:

  def mount(%{"id" => id, "guest" => guest}, _session, socket) do
    ...
    new_socket = 
      socket
      |> assign(:id, id)
      |> assign(:guest_id, guest.id)
    {:ok, new_socket}
  end