-
Notifications
You must be signed in to change notification settings - Fork 0
/
useSocket.ts
74 lines (62 loc) · 1.9 KB
/
useSocket.ts
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
import io from 'socket.io-client'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { logout, receiveMessage, updateUserList } from './SocketActions'
import { server, debounceTiming } from '../../../config/app'
import type { Message, State, UserItem } from '../../types/State'
interface SocketInterface {
socket: SocketIOClient.Socket,
sendMessage: CallableFunction,
setIsTyping: CallableFunction,
close: CallableFunction
}
const useSocket = (onLogout: CallableFunction): SocketInterface | null => {
const [socket, setSocket] = useState<SocketIOClient.Socket>()
const [lastTyping, setLastTyping] = useState(0)
const token = useSelector((state: State) => state.token)
const dispatch = useDispatch()
useEffect(() => {
const socket = io(`${server}socket`, { query: { token } })
socket.on('new message', (payload: Message) => {
dispatch(receiveMessage(payload))
})
socket.on('update userlist', (payload: UserItem[]) => {
dispatch(updateUserList(payload))
})
socket.on('inactive', () => {
socket.emit('inactive')
dispatch(logout('Disconnected due to inactivity.'))
onLogout()
})
socket.on('disconnect', () => {
socket.emit('leave')
dispatch(logout('Disconnected from server'))
onLogout()
})
setSocket(socket)
return () => {
socket.close()
}
}, [])
if (!socket) return null
return {
socket,
sendMessage: (message: string): void => {
socket.emit('new message', message)
},
setIsTyping: (): void => {
const now = Date.now()
if ((now - lastTyping) > debounceTiming) {
setLastTyping(now)
socket.emit('user typing')
}
},
close: (): void => {
socket.emit('leave')
socket.close()
dispatch(logout('Successfully logged out.'))
onLogout()
}
}
}
export default useSocket