Phoenix.LiveView.assign_new
You're seeing just the function
assign_new
, go back to Phoenix.LiveView module for more information.
Assigns a value into the socket only if it does not exist.
Useful for lazily assigning values and referencing parent assigns.
Referencing parent assigns
When a LiveView is mounted in a disconnected state, the Plug.Conn
assigns
will be available for reference via assign_new/3
, allowing assigns to
be shared for the initial HTTP request. The Plug.Conn
assigns will not be
available during the connected mount. Likewise, nested LiveView children have
access to their parent's assigns on mount using assign_new/3
, which allows
assigns to be shared down the nested LiveView tree.
Examples
# controller
conn
|> assign(:current_user, user)
|> LiveView.Controller.live_render(MyLive, session: %{"user_id" => user.id})
# LiveView mount
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
end