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
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