The useRoom hook provides access to room information and basic room operations such as manually attaching and detaching.
1
2
3
4
5
6
import { useRoom } from '@ably/chat/react';
const MyComponent = () => {
const { roomName, roomStatus } = useRoom();
return <p>Room: {roomName} ({roomStatus})</p>;
};This hook must be used within a ChatRoomProvider.
Parameters
The useRoom hook accepts an optional configuration object:
Returns
The useRoom hook returns an object with the following properties:
roomNameStringroomStatusRoomStatusroomErrorErrorInfo or UndefinedconnectionStatusConnectionStatusconnectionErrorErrorInfo or Undefinedattachattach()detachdetach()Attach to a room
attach(): Promise<void>Attach to the room to start receiving messages and events. The ChatRoomProvider handles this automatically; this method is only needed for manual lifecycle control.
Returns
Promise<void>
Returns a promise. The promise is fulfilled when the room is attached, or rejected with an ErrorInfo object.
Detach from a room
detach(): Promise<void>Detach from the room to stop receiving messages and events. Existing subscriptions are preserved but will not receive events until the room is re-attached. The ChatRoomProvider handles this automatically; this method is only needed for manual lifecycle control.
Returns
Promise<void>
Returns a promise. The promise is fulfilled when the room is detached, or rejected with an ErrorInfo object.
RoomStatus
The status of a chat room.
Initializinginitializing.Initializedinitialized.AttachingAttached, Suspended, or Failed. The value is attaching.Attachedattached.DetachingDetached or Failed. The value is detaching.Detacheddetached.Suspendedsuspended.Failedfailed.Releasingreleasing.Releasedreleased.RoomStatusChange
Describes a change in room status.
currentRoomStatuspreviousRoomStatuserrorErrorInfo or UndefinedExample
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { RoomStatus } from '@ably/chat';
import { useRoom } from '@ably/chat/react';
function RoomHeader() {
const { roomName, roomStatus, roomError } = useRoom({
onStatusChange: (change) => {
console.log(`Room status: ${change.previous} -> ${change.current}`);
},
});
return (
<header>
<h2>{roomName}</h2>
<span>{roomStatus}</span>
{roomStatus === RoomStatus.Failed && roomError && (
<p>Error: {roomError.message}</p>
)}
</header>
);
}