From 349c05d38daf3dd18c46c06f6342a6e50f7412d7 Mon Sep 17 00:00:00 2001 From: Sonia Appasamy Date: Thu, 24 Aug 2023 11:18:38 -0400 Subject: [PATCH] client/web: refresh on tab focus Refresh node data when user switches to the web client browser tab. This helps clean up the auth flow where they're sent to another tab to authenticate then return to the original tab, where the data should be refreshed to pick up the login updates. Updates tailscale/corp#13775 Signed-off-by: Sonia Appasamy --- client/web/src/hooks/node-data.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/client/web/src/hooks/node-data.ts b/client/web/src/hooks/node-data.ts index 38fe9129c..2369b4d57 100644 --- a/client/web/src/hooks/node-data.ts +++ b/client/web/src/hooks/node-data.ts @@ -38,7 +38,7 @@ export default function useNodeData() { const fetchNodeData = useCallback(() => { apiFetch("/api/data") .then((r) => r.json()) - .then((data) => setData(data)) + .then((d) => setData(d)) .catch((error) => console.error(error)) }, [setData]) @@ -114,8 +114,21 @@ export default function useNodeData() { ) useEffect( - fetchNodeData, - // Initial data load. + () => { + // Initial data load. + fetchNodeData() + + // Refresh on browser tab focus. + const onVisibilityChange = () => { + document.visibilityState === "visible" && fetchNodeData() + } + window.addEventListener("visibilitychange", onVisibilityChange) + return () => { + // Cleanup browser tab listener. + window.removeEventListener("visibilitychange", onVisibilityChange) + } + }, + // Run once. [] )