LiveVue
1.0
Server Events
Server-to-client communication using
push_event/3
on the server and
useLiveEvent()
on the client for real-time notifications and updates.
What this example shows
defmodule MyAppWeb.ServerEventsLive do
use MyAppWeb, :live_view
def render(assigns) do
~H"""
<.vue
notification_count={@notification_count}
v-component="ServerEvents"
v-socket={@socket}
/>
"""
end
def mount(_params, _session, socket) do
{:ok, assign(socket, notification_count: 0)}
end
def handle_event("trigger_notification", %{"type" => type}, socket) do
notification = %{
id: System.unique_integer([:positive]),
type: type,
message: notification_message(type),
timestamp: System.system_time(:second)
}
{:noreply,
socket
|> push_event("notification", notification)
|> update(:notification_count, &(&1 + 1))}
end
def handle_event("trigger_alert", %{"message" => message}, socket) do
alert = %{
id: System.unique_integer([:positive]),
message: message,
timestamp: System.system_time(:second)
}
{:noreply, push_event(socket, "alert", alert)}
end
defp notification_message("info"), do: "This is an informational notification"
defp notification_message("success"), do: "Operation completed successfully!"
defp notification_message("warning"), do: "Please review your settings"
defp notification_message("error"), do: "An error occurred, please try again"
defp notification_message(_), do: "New notification"
end
How it works
1 Server pushes events to client
Use push_event/3
in LiveView to send data to the client. The first argument is the socket,
the second is the event name, and the third is the payload.
push_event(socket, "notification", %{message: "Hello!"})
2 useLiveEvent() listens for events
The useLiveEvent()
composable registers a listener for server events. It automatically handles cleanup
when the component unmounts.
useLiveEvent('notification', (data) => { /* handle event */ })
3 Multiple event types
You can use different event names for different types of server pushes.
Each useLiveEvent()
call can listen to a specific event type.
useLiveEvent('notification', handleNotification)
useLiveEvent('alert', handleAlert)
4 Triggered by any handle_event
Server events can be pushed from any
handle_event/3
callback. This example triggers them from button clicks, but they could come from
background processes, PubSub, or any other source.
def handle_event("trigger", _, socket) do
{:noreply, push_event(socket, "event_name", data)}
end