Events
Event Handling
pushEvent from React reaches handle_event on the server
- useLiveReact
- pushEvent
Key concepts
useLiveReact()
gives a component access to pushEvent
without it being passed
down as a prop. Calling it sends a message over the socket exactly
as a phx-click
or a form submit would.
defmodule MyAppWeb.EventsLive do
use MyAppWeb, :live_view
def mount(_params, _session, socket) do
{:ok, assign(socket, :items, [])}
end
def render(assigns) do
~H"""
<.react name="Events" items={@items} socket={@socket} />
"""
end
def handle_event("add_item", %{"body" => body}, socket) do
item = %{id: System.unique_integer([:positive]), body: body}
{:noreply, assign(socket, :items, socket.assigns.items ++ [item])}
end
endHow it works
Submitting the form calls pushEvent
with the event name "add_item"
and the typed text as its payload, which reaches handle_event("add_item", …)
on the server. The
server appends the item to its own items
assign and reassigns
it — LiveReact diffs the new list against the old one and only sends
what changed.
The event name and payload are entirely up to the component; nothing
about this is specific to lists or to this example. Any handle_event/3
clause the LiveView already has can be reached the same way.