diff options
Diffstat (limited to 'modern/src')
-rw-r--r-- | modern/src/SocketController.js | 13 | ||||
-rw-r--r-- | modern/src/reactHelper.js | 9 |
2 files changed, 20 insertions, 2 deletions
diff --git a/modern/src/SocketController.js b/modern/src/SocketController.js index ae82d134..886ae15b 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,6 +67,12 @@ const SocketController = () => { dispatch(devicesActions.refresh(await response.json())); } connectSocket(); + return () => { + const socket = socketRef.current; + if (socket) { + socket.close(); + } + } } else { const response = await fetch('/api/session'); if (response.ok) { diff --git a/modern/src/reactHelper.js b/modern/src/reactHelper.js index f3ef78dd..7503360a 100644 --- a/modern/src/reactHelper.js +++ b/modern/src/reactHelper.js @@ -9,7 +9,14 @@ export const usePrevious = (value) => { }; export const useEffectAsync = (effect, deps) => { + const ref = useRef(); useEffect(() => { - effect(); + effect().then((result) => ref.current = result); + return () => { + const result = ref.current; + if (result) { + result(); + } + }; }, deps); }; |