How to take leverage from on_mount to reduce code
Phoenix LiveView has implemented some cool features, and one of them is the on_mount/1 callback function.
This callback function will run before the mount/3 function in your LiveView.
There are two ways to set the on_mount callback function:
- In router using live_session/3.
- In your LiveView modules with on_mount macro.
If you need to do something before the mount/3 in all your LiveViews, live_session/3 is likely the best fit. However, if it isonly for a few them, the on_mount macro will be better for your needs.
on_mount is helpful for reducing repetitive code in your LiveViews. Let’s look at an example.
defmodule ExampleWeb.UserHook do
import Phoenix.LiveView
def on_mount(:default, _params, %{"current_user" => current_user} = _session, socket) do
if authorized?(current_user) do
{:cont, socket}
else
{:halt, socket}
end
end
def on_mount(:admin, _params, %{"current_user" => current_user} = _session, socket) do
if admin?(current_user) do
{:cont, socket}
else
{:halt, socket}
end
end
end
The live_session/3 on Router:
live_session :default, on_mount: ExampleWeb.UserHook do
scope "/", ExampleWeb do
pipe_through [:browser, :auth]
live "/", HomeLive, :page
end
end
The on_mount macro:
defmodule ExampleWeb.HomeLive do
use ExampleWeb, :live_view
on_mount {ExampleWeb.UserHook, :admin}
def mount(_params, _session, socket) do
# ...
end
end
Tweet