From d46dfcf82e5fe77b9d18b4a3732cd564e1f853b2 Mon Sep 17 00:00:00 2001 From: Carlos Valente Date: Fri, 13 Dec 2024 11:02:07 +0100 Subject: [PATCH] refactor: improve redirect --- apps/client/src/common/hooks/useClientPath.ts | 15 +++++++++++---- apps/client/src/common/hooks/useSocket.ts | 9 +++++++++ apps/client/src/common/utils/socket.ts | 1 - 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/apps/client/src/common/hooks/useClientPath.ts b/apps/client/src/common/hooks/useClientPath.ts index 4c0d7b866..917b3de72 100644 --- a/apps/client/src/common/hooks/useClientPath.ts +++ b/apps/client/src/common/hooks/useClientPath.ts @@ -4,16 +4,23 @@ import { useLocation, useNavigate } from 'react-router-dom'; import { useClientStore } from '../stores/clientStore'; import { socketSendJson } from '../utils/socket'; +import { useIsOnline } from './useSocket'; + export const useClientPath = () => { const navigate = useNavigate(); const { pathname, search } = useLocation(); - const redirect = useClientStore((store) => store.redirect); - const setRedirect = useClientStore((store) => store.setRedirect); + const { redirect, setRedirect } = useClientStore((store) => ({ + redirect: store.redirect, + setRedirect: store.setRedirect, + })); + const isOnline = useIsOnline(); // notify of client path changes useEffect(() => { + if (!isOnline) return; + socketSendJson('set-client-path', pathname + search); - }, [pathname, search]); + }, [pathname, search, isOnline]); // navigate to new path when received from server useEffect(() => { @@ -26,7 +33,7 @@ export const useClientPath = () => { // navigate if there is a path change if (redirect !== pathname + search) { - navigate(redirect); + navigate(redirect, { replace: true }); } }, [navigate, pathname, redirect, search, setRedirect]); }; diff --git a/apps/client/src/common/hooks/useSocket.ts b/apps/client/src/common/hooks/useSocket.ts index a990bacc9..ee56a8b5a 100644 --- a/apps/client/src/common/hooks/useSocket.ts +++ b/apps/client/src/common/hooks/useSocket.ts @@ -238,3 +238,12 @@ export const usePing = () => { return useRuntimeStore(featureSelector); }; + +/** convert ping into a derived value which changes less often */ +export const useIsOnline = () => { + const featureSelector = (state: RuntimeStore) => ({ + isOnline: state.ping > 0, + }); + + return useRuntimeStore(featureSelector); +}; diff --git a/apps/client/src/common/utils/socket.ts b/apps/client/src/common/utils/socket.ts index 6b7f26c3b..4af7af816 100644 --- a/apps/client/src/common/utils/socket.ts +++ b/apps/client/src/common/utils/socket.ts @@ -39,7 +39,6 @@ export const connectSocket = () => { } socketSendJson('set-client-type', 'ontime'); - socketSendJson('set-client-path', location.pathname + location.search); setOnlineStatus(true); };