aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnton Tananaev <anton.tananaev@gmail.com>2021-09-06 11:59:42 -0700
committerAnton Tananaev <anton.tananaev@gmail.com>2021-09-06 11:59:42 -0700
commit40e9d7dda120ab6b3bdb844c08e6eacb2212dda2 (patch)
treeb16edd2395820afe1e9a619f3a495292e9979bf3
parent158f8ba27f354b53f4d25613d1ff1828cbad0bea (diff)
downloadtrackermap-web-40e9d7dda120ab6b3bdb844c08e6eacb2212dda2.tar.gz
trackermap-web-40e9d7dda120ab6b3bdb844c08e6eacb2212dda2.tar.bz2
trackermap-web-40e9d7dda120ab6b3bdb844c08e6eacb2212dda2.zip
Close socket on logout (fix #896)
-rw-r--r--modern/src/SocketController.js13
-rw-r--r--modern/src/reactHelper.js9
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);
};