LiveVue 1.0
Examples Server Events

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

1
push_event
Server sends to client
2
useLiveEvent()
Client receives events
3
Multiple Events
Different event types
Trigger server notifications
Trigger server alerts
Notifications
total
No notifications yet
Alerts
Recent 3
No alerts yet

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
Next up: Navigation with Link component
Navigation →