forked from nathydre21/nepa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSocket.ts
More file actions
75 lines (63 loc) · 1.89 KB
/
useSocket.ts
File metadata and controls
75 lines (63 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { useEffect, useRef, useState, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
interface SocketConfig {
url?: string;
token?: string;
autoConnect?: boolean;
}
export const useSocket = ({ token }: { token: string | null }) => {
const socketRef = useRef<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
const [lastMessage, setLastMessage] = useState<any>(null);
useEffect(() => {
if (!token) return;
const socketUrl = process.env.REACT_APP_API_URL || 'http://localhost:3001';
// Initialize socket connection
socketRef.current = io(socketUrl, {
auth: { token },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000,
transports: ['websocket', 'polling']
});
// Connection events
socketRef.current.on('connect', () => {
setIsConnected(true);
console.log('✅ Socket connected');
});
socketRef.current.on('disconnect', (reason) => {
setIsConnected(false);
console.log('❌ Socket disconnected:', reason);
});
socketRef.current.on('connect_error', (err) => {
console.error('Socket connection error:', err.message);
setIsConnected(false);
});
// Global notification listener
socketRef.current.on('notification', (data) => {
setLastMessage(data);
});
return () => {
if (socketRef.current) {
socketRef.current.disconnect();
}
};
}, [token]);
// Helper to subscribe to specific events
const subscribe = useCallback((event: string, callback: (data: any) => void) => {
if (socketRef.current) {
socketRef.current.on(event, callback);
}
return () => {
if (socketRef.current) {
socketRef.current.off(event, callback);
}
};
}, []);
return {
socket: socketRef.current,
isConnected,
lastMessage,
subscribe
};
};