How to Pass Arbitrary Values Into a LiveSession

A phone laying next to the trackpad on a laptop, with a cup of coffee in the background
Pat Collins

Engineer

Pat Collins

You need to stay ahead of the competition. Elixir can help you do that, and we can show you how. Book a free consult today to learn how.

Sometimes it’s helpful to be able to pass simple values through to a group of LiveViews. This could be for any number of reasons. Here are a few examples:

  • You want to support switching between pre-set themes with your styles.
  • You want to only turn on a feature in certain section of your app.

Today I learned you can do this using live_session and its session option. For example, here we can set the theme for the admin portion of our app:

scope "/admin", MyAppWeb.Admin, as: :admin do
  live_session :admin, session: %{"theme" => "admin"}, on_mount: MyAppWeb.RequireAdminUser do
    live "/", DashboardLive, :show
    live "/assets", AssetsLive, :index
    live "/pages", PagesLive, :index
  end
end

Then in the LiveView:

@impl Phoenix.LiveView
def mount(_params, %{"theme" => theme} = _session, socket) do
  {:ok, assign(socket, :theme, theme)}
end

This is great for cases where you need to pass in some simple state to a group of LiveViews without a lot of ceremony.

Sources:

Newsletter

Stay in the Know

Get the latest news and insights on Elixir, Phoenix, machine learning, product strategy, and more—delivered straight to your inbox.

Narwin holding a press release sheet while opening the DockYard brand kit box