Events
Broadcast ephemeral events to the other clients connected to a room. Events contain custom JSON data and are not persisted after they’re sent, meaning only connected clients receive them. Use them to trigger toast notifications, render emoji reactions, send play/pause signals, tell clients to refresh API data, and more.
Setting up an event
Before sending an event, make sure to set the RoomEvent type in your config
file, using a union for multiple events. Any JSON data can be defined and
sent—in this example, two events are defined, a "REACTION" event and a
"PLAY" event.
useBroadcastEvent
allows you to send a custom event to everyone else in the room, for example an
emoji reaction.
useEventListener
allows you to listen for sent events and react to them, for example the
"REACTION" event sent above.
The callback also receives the user that sent the event, and their
connectionId. Note that the sender does not receive their own event.
Broadcast from the server
Send events from your back end with
Liveblocks.broadcastEvent
or the
Broadcast event REST API,
and every client will receive them in realtime.
When an event comes from the server, listeners receive a connectionId of -1
and a user of null.
Revalidate server data
A common pattern is broadcasting an event after changing data on your server, so
every client refetches it immediately. In combination with a data-fetching
package like SWR, call its mutate when the event
arrives.
Read about revalidating API data in realtime for a complete example.