LiveView calls mount two times

Hello,
here is an excerpt of the way I’m handling it (means it is ok for my needs) :

  def mount(params, session, socket) do
    case connected?(socket) do
      true -> connected_mount(params, session, socket)
      false -> {:ok, assign(socket, page: "loading")}
    end
  end

  def connected_mount(_params, %{"page" => "dashboard" = page, "user_id" => user_id}, socket) do
    
    <** YOUR BIG SQL HERE THAT YOU WANT EXECUTED ONLY ONCE CONNECTED **>

    {:ok, assign(socket, 
    
       <** YOUR ASSIGNMENTS HERE **>
    
    )}
  end

  def connected_mount(_params, _session, socket) do
    {:ok, assign(socket, page: "error")}
  end


  def render(%{page: "loading"} = assigns) do
    ~L"<div>La page est en cours de chargement, veuillez patienter...</div>"
  end

  def render(%{page: "error"} = assigns) do
    ~L"<div>Une erreur s'est produite</div>"
  end

  def render(%{page: page} = assigns) do
    Phoenix.View.render(KandeskWeb.LiveView, "page_" <> page <> ".html", assigns)
  end

Please note that the liveview is called from router via :
live "/", IndexLive, session: %{"page" => "dashboard"}

Cheers,
Sébastien

14 Likes