Presence
Presence is a per-connection state that allows users to track what other users are doing in the same room. Presence can be used to represent movement, selections, and characteristics of a user, and can be really important to building collaborative experiences.
Set presence
To get started with presence for pluv.io, first set a presence
config on your createRoomBundle
config.
1import { createBundle, createClient } from "@pluv/react";2import type { AppPluvIO } from "backend/io";3import { z } from "zod";45const client = createClient<AppPluvIO>({6 wsEndpoint: (room) => `${process.env.WS_ENDPOINT}/api/room/${room}`,7});89const pluv = createBundle(client);1011export const pluvRoom = pluv.createRoomBundle({12 // Define the validation schema for presence, using zod13 presence: z.object({14 selectionId: z.nullable(z.string()),15 }),16});
Set initialPresence on PluvRoomProvider
1import { FC } from "react";2import { pluvRoom } from "frontend/io";34const Room: FC = () => {5 return (6 <pluvRoom.PluvRoomProvider7 // Specify the initial presence for each newly connected user8 initialPresence={{9 selectionId: null,10 }}11 room="my-example-room"12 >13 <ChatRoom />14 </pluvRoom.PluvRoomProvider>15 );16};
Observing presence
Current user's presence
1import { pluvRoom } from "frontend/io";2import { useCallback } from "react";34const [myPresence, updateMyPresence] = pluvRoom.useMyPresence();5// ^? const myPresence: { selectionId: string | null } | null67const myself = pluvRoom.useMyself();8// ^? const myself: {9// connectionId: string;10// presence: { selectionId: string | null };11// user: null;12// } | null;1314// Updating the current user's presence15const selectInput = useCallback((selectionId: string) => {16 updateMyPresence(selectionId);17}, [updateMyPresence]);
Others' presence
1import { pluvRoom } from "frontend/io";23const others = pluvRoom.useOthers();4// ^? const others: readonly {5// connectionId: string;6// presence: { selectionId: string | null };7// user: null;8// } | null;910// const connectionId = others[0]?.connectionId!;1112const other = pluvRoom.useOther(connectionId);13// ^? const other: {14// connectionId: string;15// presence: { selectionId: string | null };16// user: null;17// } | null;