aboutsummaryrefslogtreecommitdiff
path: root/modern/src/SocketController.js
diff options
context:
space:
mode:
Diffstat (limited to 'modern/src/SocketController.js')
-rw-r--r--modern/src/SocketController.js25
1 files changed, 18 insertions, 7 deletions
diff --git a/modern/src/SocketController.js b/modern/src/SocketController.js
index ae82d134..ac950190 100644
--- a/modern/src/SocketController.js
+++ b/modern/src/SocketController.js
@@ -1,3 +1,4 @@
+import { useRef } from 'react';
import { useDispatch, useSelector, connect } from 'react-redux';
import { useHistory } from 'react-router-dom';
@@ -24,13 +25,17 @@ const displayNotifications = (events) => {
const SocketController = () => {
const dispatch = useDispatch();
const history = useHistory();
+
const authenticated = useSelector((state) => !!state.session.user);
+ const socketRef = useRef();
+
const connectSocket = () => {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const socket = new WebSocket(`${protocol}//${window.location.host}/api/socket`);
+ socketRef.current = socket;
- socket.onclose = () => {
+ socket.onerror = () => {
setTimeout(() => connectSocket(), 60 * 1000);
};
@@ -62,14 +67,20 @@ const SocketController = () => {
dispatch(devicesActions.refresh(await response.json()));
}
connectSocket();
+ return () => {
+ const socket = socketRef.current;
+ if (socket) {
+ socket.close();
+ }
+ };
+ }
+ const response = await fetch('/api/session');
+ if (response.ok) {
+ dispatch(sessionActions.updateUser(await response.json()));
} else {
- const response = await fetch('/api/session');
- if (response.ok) {
- dispatch(sessionActions.updateUser(await response.json()));
- } else {
- history.push('/login');
- }
+ history.push('/login');
}
+ return null;
}, [authenticated]);
return null;