//Broadcasting events

Broadcasting events

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:

  • Creating state controls, for example “next/previous slide” buttons in presentations
  • Letting other users know when to revalidate data after a change
  • Sending short-lived chat messages to other users

On this page, we’ll be using events to send toast notifications to other users.

Setting up types

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.

// Event typestype RoomEvent = {  type: "TOAST";  message: string;};

Broadcasting the events

Events can be broadcast to other users with the useBroadcastEvent hook. Switch to Room.tsx and add the hook, imported from our config file.

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

return (  <button    onClick={() =>      // Broadcast toast event      broadcast({ type: "TOAST", message: "Event received!" })    }  >    Broadcast event  </button>);

Listening for events

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.

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

Edit this page
Helpful?