LiveView: The basics
LiveView is an extension of the Phoenix Framework designed for building real-time, lightweight, interactive web views. It processes most of its logic on the server, minimizing the need for JavaScript, thereby reducing code complexity and enhancing performance.
Live-view functions
mount/3
Initiates the LiveView by setting up the initial state and handling session data. This setup might involve making synchronous calls to a database to retrieve initial data or verifying user permissions to view certain information.
-
{:ok, socket}
: The most common response. Initializes the state and prepares the socket for the session, ensuring the LiveView is ready to render and manage updates. -
{:halt, socket}
: Halts the LiveView process before it becomes active. Used when initial conditions, such as insufficient permissions makes it impossible to render the view. This triggers the supervisor’s recovery logic. -
{:stop, reason, socket}
: Stops the LiveView process and provides a reason for the termination,allowing the supervisor to recover in the context of that termination.
handle_params/3
Happens after the mount
. This optional function parses URL params for pagination, filters, or specific item views.
-
{:noreply, socket}
: The most common response, updates the process’s state andlive-view
handles changes to the DOM. -
{:reply, reply, socket}
: Updates the process’s state, but also immediately sends information to the client outside of thelive-view
DOM rendering, such as sending a event to trigger a JavaScript function to display an alert. -
{:halt, socket}
and{:stop, reason, socket}
: These are the same asmount/3
handle_event/3
Optional, handles events triggered by interactions within the LiveView, such as button clicks or form submissions enabling client actions to initiate server-side events. The return tuples match handle_params/3
.
handle_info/2
Handles asynchronous messages from outside sources, such as other LiveViews, system notifications, and scheduled tasks. The response handling for handle_info/2
aligns with handle_params/3
and handle_event/3
.
Example
defmodule GameAppWeb.PlayerLive.Index do
use GameAppWeb, :live_view
alias GameApp.Accounts
alias GameApp.Accounts.Player
def mount(_params, _session, socket) do
{:ok, stream(socket, :players, Accounts.list_players())}
end
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
def handle_event("delete", %{"id" => id}, socket) do
player = Accounts.get_player!(id)
{:ok, _} = Accounts.delete_player(player)
{:noreply, stream_delete(socket, :players, player)}
end
def handle_info({GameAppWeb.PlayerLive.FormComponent, {:saved, player}}, socket) do
{:noreply, stream_insert(socket, :players, player)}
end
defp apply_action(socket, :edit, %{"id" => id}) do
current_player = Accounts.get_player!(id)
socket
|> assign(:page_title, "Edit Player")
|> assign(:player, current_player)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Player")
|> assign(:player, %Player{})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Players")
|> assign(:player, nil)
end
end
Mount Function
The mount
function initializes the LiveView by setting up a stream with a list of players retrieved via Accounts.list_players()
. This establishes the initial data flow and prepares the LiveView to render the user interface.
URL Parameter Handling
handle_params
parses URL parameters to dynamically adjust the LiveView’s state based on user navigation. This includes handling routes for viewing all players (/players
), creating a new player (/players/new
), or editing an existing player (/players/1/edit
).
Event Handling
The handle_event
function responds to client-side actions, such as a delete button press. It manages the deletion of a player from the database and updates the stream to reflect this change in the UI.
Handling External Messages
The player form, managed by a separate LiveView component, communicates back to this LiveView when player information is saved. The handle_info
function processes this incoming data, updating the player stream with the new or updated player information.
Error Handling and Control Flow
Rather than using {:halt, socket}
, this code uses an indirect control flow Accounts.get_player!
, which throws an exception, which halts the LiveView process, prompting the supervisor.