Another key feature of Liveblocks is the ability to broadcast custom events to other users. Events are ephemeral, and are sent to all users currently connected to the room, which makes them useful for:
On this page, we’ll be using events to send toast notifications to other users.
The first step in broadcasting events is setting up your types. Let’s navigate
to liveblocks.config.ts and create a RoomEvent type for our toasts.
RoomEvent represents the object that will be broadcast to other users
currently connected to the room. We’ll give it a type along with a message
that can appear in the toast notification.
/liveblocks.config.ts// Event typesRoomEvent: { type: "TOAST"; message: string;}If your app uses multiple event types, you can make RoomEvent a union type.
Events can be broadcast to other users with the useBroadcastEvent hook.
Switch to Room.tsx and add the hook, imported from our config file.
/Room.tsx// Broadcast event hookconst broadcast = useBroadcastEvent();In the onClick event, pass an object to broadcast that matches the
RoomEvent type specified above—this is how we send an event to other users.
/Room.tsxreturn ( <button onClick={() => // Broadcast toast event broadcast({ type: "TOAST", message: "Event received!" }) } > Broadcast event </button>);We’re now sending an event, but we’re not listening for any. Import
useEventListener and add it to the component. In the callback, we’re
checking if the received event is a toast notification, and if it is, we’re
calling a function that sends a toast notification with the message.
/Room.tsx// Listen for incoming eventsuseEventListener(({ event }) => { if (event.type === "TOAST") { toast(event.message); }});Try pressing the button to see other users receive toast notifications! You can
also change the message and see an updated notification appear.
We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.