Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/hooks/useTruco.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
import { socketService } from '../services/socketService';
import { useSocketContext } from '../contexts/SocketContext';
import type { TrucoAction, TrucoEvent, TrucoState } from '../types/truco';

export type Bubble = { ev: TrucoEvent; id: number };
Expand All @@ -10,7 +9,6 @@ let seq = 0;

// Estado de la mesa de truco. Se monta al tope de la página: el server manda truco:state apenas empieza
export function useTruco(lobbyId: string) {
const { isConnected } = useSocketContext();
const [state, setState] = useState<TrucoState | null>(null);
const [bubbles, setBubbles] = useState<Record<number, Bubble>>({});
const [handPoints, setHandPoints] = useState<Puntos[]>([]);
Expand Down Expand Up @@ -44,8 +42,7 @@ export function useTruco(lobbyId: string) {
};
socketService.on('truco:state', onState);
return () => socketService.off('truco:state', onState);
// isConnected: en una recarga el socket se crea después del primer render
}, [lobbyId, isConnected]);
}, [lobbyId]);

const act = useCallback((action: TrucoAction) => socketService.trucoAct(lobbyId, action).catch(() => {}), [lobbyId]);

Expand Down
18 changes: 10 additions & 8 deletions src/services/socketService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,13 @@ export interface SocketEvents {
'connect_error': (error: Error) => void;
}

type Listener = Parameters<Socket['on']>[1];

class SocketService {
private socket: Socket | null = null;
// Listeners registrados aunque el socket todavía no exista (al abrir o recargar una página,
// sus efectos corren antes de que el SocketProvider conecte). Se enganchan al crear el socket.
private listeners: [string, Listener][] = [];

connect(): Promise<Socket> {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -106,6 +111,7 @@ class SocketService {
reconnectionDelay: 1000,
auth: { token: getSessionToken() },
});
for (const [event, cb] of this.listeners) this.socket.on(event, cb);

this.socket.on('connect', () => {
console.log('✅ Conectado al servidor WebSocket', { socketId: this.socket?.id });
Expand Down Expand Up @@ -265,17 +271,13 @@ class SocketService {

// Métodos para escuchar eventos
on<K extends keyof SocketEvents>(event: K, callback: SocketEvents[K]): void {
if (this.socket) {
console.debug(`socketService.on -> ${String(event)}`);
this.socket.on(event as string, callback as any);
}
this.listeners.push([event as string, callback as Listener]);
this.socket?.on(event as string, callback as Listener);
}

off<K extends keyof SocketEvents>(event: K, callback?: SocketEvents[K]): void {
if (this.socket) {
console.debug(`socketService.off -> ${String(event)}`);
this.socket.off(event as string, callback as any);
}
this.listeners = this.listeners.filter(([e, cb]) => e !== event || (callback && cb !== callback));
this.socket?.off(event as string, callback as any);
}

// Método genérico para emit (privado - usar métodos públicos async)
Expand Down
Loading