@ably/chat - v1.1.1
    Preparing search index...

    Function useOccupancy

    • React hook that provides real-time room occupancy information.

      This hook automatically tracks the number of connections and presence members in a room, updating the counts in real-time as users join and leave. It integrates with the nearest ChatRoomProvider and handles cleanup when the component unmounts.

      The hook provides both the current occupancy metrics as state values and allows you to register listeners for occupancy change events.

      Note: This hook must be used within a ChatRoomProvider component tree. Note: Room must be attached to receive real-time occupancy updates, typically the ChatRoomProvider handles this automatically.

      Parameters

      • Optionalparams: UseOccupancyParams

        Optional parameters for event listeners and room status callbacks

      Returns UseOccupancyResponse

      A UseOccupancyResponse containing current occupancy metrics and room status

      import React from 'react';
      import { ChatClient, OccupancyEvent } from '@ably/chat';
      import {
      ChatClientProvider,
      ChatRoomProvider,
      useOccupancy
      } from '@ably/chat/react';

      // Component that displays occupancy information
      const RoomOccupancy = () => {
      const {
      connections,
      presenceMembers,
      connectionStatus,
      roomStatus
      } = useOccupancy({
      listener: (occupancyEvent: OccupancyEvent) => {
      console.log('Occupancy changed:', occupancyEvent.occupancy);
      },
      onDiscontinuity: (error) => {
      console.error('Discontinuity detected:', error);
      }
      });

      return (
      <div>
      <div>👥 Total Connections: {connections}</div>
      <div>🟢 Present Members: {presenceMembers}</div>
      </div>
      );
      };

      const chatClient: ChatClient; // existing ChatClient instance

      // App component with providers
      const App = () => {
      return (
      <ChatClientProvider client={chatClient}>
      <ChatRoomProvider name="public-lobby">
      <RoomOccupancy />
      </ChatRoomProvider>
      </ChatClientProvider>
      );
      };

      export default App;