Skip to content

Comments

feat(hooks): implement useRoomSocket hook with auto-reconnect functionality#75

Draft
Copilot wants to merge 3 commits intomainfrom
copilot/fix-15
Draft

feat(hooks): implement useRoomSocket hook with auto-reconnect functionality#75
Copilot wants to merge 3 commits intomainfrom
copilot/fix-15

Conversation

Copy link
Contributor

Copilot AI commented Aug 12, 2025

This PR implements the useRoomSocket hook, a React hook that provides Socket.IO client connection management with auto-reconnect capabilities for room-based real-time communication.

Key Features

🔌 Socket.IO Integration

  • Connects to room-specific namespaces using the format room:{id}
  • Automatic connection management with proper cleanup
  • Support for multiple tabs/instances connecting to the same room

🔄 Auto-Reconnect Functionality

  • Handles network loss with automatic reconnection attempts
  • Detects tab backgrounding/foregrounding and reconnects when tab becomes visible
  • Queues emit operations during disconnected states and replays them on reconnection
  • Preserves room context across network interruptions

👤 Role Management

  • Integrates with existing RoleDetectionService for cookie-based role persistence
  • Supports organizer and guest roles with proper restoration after reconnection
  • Role information is included in socket connection configuration

📡 Event Management

  • Provides typed emit functions for all socket events:
    • emitRoomStateUpdate() - Room state changes
    • emitParticipantUpdate() - Participant additions/updates
    • emitWheelSpin() - Wheel spin events
    • emitTimerUpdate() - Timer state changes
    • emitRoomMessage() - Room messages
  • Event subscription with automatic cleanup (onStateUpdate())
  • Graceful handling of emits during reconnect states

🛡️ Validation & Error Handling

  • UUID v4 validation for room IDs with user-friendly error messages
  • Comprehensive error handling for connection failures
  • Connection state management (disconnected → connecting → connected → error)

API

const {
  status,           // Connection status
  error,            // Error message if any
  socketId,         // Socket ID when connected
  role,             // Current user role
  isConnected,      // Boolean connection state
  connect,          // Manual connect function
  disconnect,       // Manual disconnect function
  onStateUpdate,    // Subscribe to room state updates
  emitRoomStateUpdate,   // Emit room state changes
  emitParticipantUpdate, // Emit participant updates
  // ... other emit functions
} = useRoomSocket({
  roomId: 'uuid-v4-room-id',
  autoConnect: true,  // Optional
  userId: 'user-id',  // Optional
  userName: 'User',   // Optional
  url: 'ws://localhost:3000'  // Optional
})

Usage Example

function RoomComponent({ roomId }: { roomId: string }) {
  const socket = useRoomSocket({ roomId })
  
  useEffect(() => {
    if (!socket.isConnected) return
    
    // Subscribe to room state updates
    const cleanup = socket.onStateUpdate((data) => {
      console.log('Room state updated:', data)
    })
    
    return cleanup
  }, [socket.isConnected])
  
  const handleParticipantAdd = (participant) => {
    socket.emitParticipantUpdate({
      participant,
      action: 'added'
    })
  }
  
  return (
    <div>
      Status: {socket.status}
      {socket.error && <div>Error: {socket.error}</div>}
    </div>
  )
}

Testing

  • 17 comprehensive tests covering all user scenarios from the issue requirements
  • Tests cover connection management, auto-reconnect, role handling, event management, and error scenarios
  • Full test coverage with 210 total tests passing

Fixes #15.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot AI and others added 2 commits August 12, 2025 13:24
Co-authored-by: underscorekadji <3449713+underscorekadji@users.noreply.github.com>
Co-authored-by: underscorekadji <3449713+underscorekadji@users.noreply.github.com>
Copilot AI changed the title [WIP] [2.3] Socket.IO client hook (useRoomSocket) + reconnect feat(hooks): implement useRoomSocket hook with auto-reconnect functionality Aug 12, 2025
Copilot AI requested a review from underscorekadji August 12, 2025 13:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[2.3] Socket.IO client hook (useRoomSocket) + reconnect

2 participants