Best Practice for on_mount handlers?

Hi,

I am currently porting my live view toy application to 0.17. And I really like the options to use either on_mount/1 or to use the on_mount option of live_session/3 to add the standard callbacks to call when mounting a live view. Actually, there is also a third option by editing MyProjectWeb.live_view and putting the standard on_mount/1 calls there.

I am not sure, what is the best way to do that and like to ask for some advice and for a best practice.

I have 3 hooks/callbacks that should be called on every live view in my app.

  • MyProjectWeb.Hooks.PutLocale to extract the current locale from the session.
  • MyProjectWeb.Hooks.LocalTimezone to store the browser timezone.
  • MyProjectWeb.Hooks.UserLiveAuth to authenticate/check the current user.

I can solve this in three ways.

  1. Put manually on_mount/1 calls in all my live views. Very explicit and obvious, but not very DRY.
defmodule MyProjectWeb.DashboardLive do
  use MyProjectWeb, :live_view

  on_mount MyProjectWeb.Hooks.PutLocale
  on_mount MyProjectWeb.Hooks.LocalTimezone
  on_mount MyProjectWeb.Hooks.UserLiveAuth

  def render(assigns) do
    ~H"""
    """
  end
end
  1. Put it on a live_session inside router.ex. Follows a bit the pattern of the pipelines, but it just doesn’t feel right to me.
  scope "/", MyProjectWeb do
    pipe_through :browser

    live_session :default,
      on_mount: [MyProjectWeb.Hooks.PutLocale, MyProjectWeb.Hooks.LocalTimezone, MyProjectWeb.Hooks.UserLiveAuth ] do
      live "/", DashboardLive
    end
  end
  1. Add the on_mount/1 calls to MyProjectWeb.live_view. On the first look it seems to be DRY. And I only see the disadvantage, that this doesn’t work, if you have live views in your app, that don’t use all of these hooks/callbacks.
  def live_view do
    quote do
      use Phoenix.LiveView,
        layout: MyProjectWeb.LayoutView, "live.html"}

        on_mount MyProjectWeb.Hooks.PutLocale
        on_mount MyProjectWeb.Hooks.LocalTimezone
        on_mount MyProjectWeb.Hooks.UserLiveAuth

      unquote(view_helpers())
    end
  end

What is the best practice here? What do you do in your projects?

Cheers,
Oliver

4 Likes