forked from RenaudLN/dash_socketio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DashSocketIO.tsx
91 lines (77 loc) · 2.51 KB
/
DashSocketIO.tsx
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import React, { useState } from 'react';
import { io } from 'socket.io-client';
import { DashComponentProps } from '../props';
type Props = {
url: string,
debug?: boolean,
send?: object,
} & DashComponentProps;
const DashSocketIO = (props: Props) => {
const { url, send, debug = false, setProps } = props;
const [socketId, setSocketId] = useState<string | null>(null);
const [connected, setConnected] = useState<boolean>(false);
const socket = React.useMemo(() => io(
url || undefined, { auth: { pathname: window.location.pathname } }
), [url])
React.useEffect(() => {
const onConnect = () => {
if (debug) {
console.log(`Connected at ${new Date().toISOString()}`)
}
setSocketId(socket.id);
setConnected(true);
}
const onDisconnect = () => {
if (debug) {
console.log(`Disconnected at ${new Date().toISOString()}`)
}
setSocketId(null);
setConnected(false);
}
const onEvent = (event: object) => {
if (debug) {
console.log(`Event received at ${new Date().toISOString()} - ${JSON.stringify(event)}`)
}
for (const [key, value] of Object.entries(event)) {
var data_key = `data-${key}`
if (debug) {
console.log(`Setting ${data_key} to ${value}`)
}
// Jim: In case the suuplied value equals the current value, we need to set it to null first
// otherwise react won't update the value in the frontend as there is no change.
// I don't think this incurs a performance penalty but please correct me if I'm wrong.
setProps({ [data_key]: null })
setProps({ [data_key]: value })
}
}
socket.on('connect', onConnect);
socket.on('disconnect', onDisconnect);
socket.on("ws-event", onEvent);
return () => {
socket.off('connect', onConnect);
socket.off('disconnect', onDisconnect);
socket.off("ws-event", onEvent);
socket.disconnect();
};
}, [socket]);
React.useEffect(() => {
if (socket && send) {
const event = send['event'];
const data = send['data'];
if (data) {
if (debug) {
console.log(`Sending event ${event} at ${new Date().toISOString()} - ${JSON.stringify(data)}`)
}
socket.emit(event, data);
} else {
if (debug) {
console.log(`Sending event ${event} at ${new Date().toISOString()}`)
}
socket.emit(event);
}
}
}, [send]);
return null;
}
DashSocketIO.defaultProps = {};
export default DashSocketIO;