LiveView 'plug' for shared logic?

I was wondering, imagine you have several (but not all) LiveViews where in the upon mount you would want to place some shared logic. For instance, you have an internal contract that every liveview will have a internal_id param on the session.

For now, in every LV I have code to fetch that value, transform it and put it on the socket assigns.

I was wondering if there would be a Plug-like alternative, where in the LV I could say

plug LiveViewHelpers.get_internal_id

Which would be called just prior to mount and update the assigns, to then call mount itself with the updated socket; kind of how plugs work in front of Phoenix controllers?

1 Like

The on_mount macro can do that and you can use live_session for sharing those across LV routes.

2 Likes

Thanks. I will look into that macro!

In router.ex

live_session :customer_portal,on_mount: [
    {AmplifyWeb.UnifiedUserAuth, :require_authenticated},
  ] do
  live "/portal/dashboard", CustomerPortalDashboard
end

In UnifiedUserAuth

def on_mount(:require_authenticated, _params, session, socket) do
    socket = mount_current_scope(socket, session)

    if socket.assigns.current_scope && socket.assigns.current_scope.unified_user do
      {:cont, socket}
    else
      socket =
        socket
        |> Phoenix.LiveView.put_flash(:error, "You must log in to access this page.")
        |> Phoenix.LiveView.redirect(to: ~p"/unified_users/log-in")

      {:halt, socket}
    end
  end
2 Likes