In a liveview 1.7 app the code below works as expected. This makes the portion of the DOM render only when the user is authenticated.
defmodule AppWeb.Landing do
use AppWeb, :live_view
on_mount {AppWeb.UserAuth, :mount_current_user} # Important part
def mount(_params, _session, socket) do
{:ok, socket}
end
def render(assigns) do
~H"""
<div class="h-screen">
<%= if @current_user do %>
<h1>this is text for auth check</h1>
<% end %>
</div>
"""
end
end
When I place the exact same code in a new phoenix 1.8 instance I get this:
[error] ** (FunctionClauseError) no function clause matching in AppWeb.UserAuth.on_mount/4
(app 0.1.0) lib/app_web/user_auth.ex:156: AppWeb.UserAuth.on_mount(:mount_current_user, %{}, %{"_csrf_token" => "vkKX5N_I4AZCmGNG1yDUnxQ5"}, #Phoenix.LiveView.Socket<id: "phx-GDgk8lYlgWTv4AbE", endpoint: AppWeb.Endpoint, view: AppWeb.Landing, parent_pid: nil, root_pid: nil, router: AppWeb.Router, assigns: %{__changed__: %{}, flash: %{}, live_action: :home}, transport_pid: nil, ...>)
(phoenix_live_view 1.0.9) lib/phoenix_live_view/lifecycle.ex:158: anonymous fn/4 in Phoenix.LiveView.Lifecycle.mount/3
(phoenix_live_view 1.0.9) lib/phoenix_live_view/lifecycle.ex:237: Phoenix.LiveView.Lifecycle.reduce_socket/3
(phoenix_live_view 1.0.9) lib/phoenix_live_view/utils.ex:346: anonymous fn/6 in Phoenix.LiveView.Utils.maybe_call_live_view_mount!/5
The on_mount function (shown below) is in the file named user_auth.ex and under the module named: AppWeb.UserAuth
def on_mount(:mount_current_scope, _params, session, socket) do
{:cont, mount_current_scope(socket, session)}
end