-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSocket.ts
More file actions
56 lines (52 loc) · 1.42 KB
/
useSocket.ts
File metadata and controls
56 lines (52 loc) · 1.42 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
import { useEffect, useRef, useState } from 'react'
import { useContext } from 'react'
import { SocketContext } from 'context/socketManager'
import { Socket } from 'socket.io-client'
interface useSocketProps {
nsp: string
onConnect?: (socket: Socket) => void
onUnmounted?: (socket: Socket) => void
onMounted?: (socket: Socket) => void
}
const useSocket = ({ nsp, onConnect, onUnmounted, onMounted }: useSocketProps) => {
const { manager } = useContext(SocketContext)
const [isError, setIsError] = useState<string | null>(null)
const socket = useRef(
manager.create_socket(nsp, {
auth: {
token: localStorage.getItem('_PLUG_AUTH_') || '',
},
}),
)
useEffect(() => {
if (socket.current) {
socket.current.listen('connect_error', ({ message }: Error) => {
if (!isError) {
setIsError(message)
}
})
socket.current.listen('connect', () => {
if (isError) {
setIsError(null)
}
onConnect && onConnect(socket.current)
})
}
}, [socket.current, isError])
useEffect(() => {
if (socket.current) {
onMounted && onMounted(socket.current)
}
return () => {
onUnmounted && onUnmounted(socket.current)
}
}, [socket.current])
return {
manager,
socket: socket.current,
isError,
isConnected: socket.current.connected,
isLoading: !socket.current,
}
}
export default useSocket