From ff54d0182e84be4812c48f8b1d0e154de2d86dfa Mon Sep 17 00:00:00 2001 From: J M Rossy Date: Mon, 27 May 2024 11:10:05 -0400 Subject: [PATCH] Avoid refetching when window is not visibile --- src/features/messages/queries/useMessageQuery.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/features/messages/queries/useMessageQuery.ts b/src/features/messages/queries/useMessageQuery.ts index 4d88ef1..7cfa6ed 100644 --- a/src/features/messages/queries/useMessageQuery.ts +++ b/src/features/messages/queries/useMessageQuery.ts @@ -65,9 +65,8 @@ export function useMessageSearchQuery( // Setup interval to re-query const reExecutor = useCallback(() => { - if (query && isValidInput) { - reexecuteQuery({ requestPolicy: 'network-only' }); - } + if (!query || !isValidInput || !isWindowVisible()) return; + reexecuteQuery({ requestPolicy: 'network-only' }); }, [reexecuteQuery, query, isValidInput]); useInterval(reExecutor, SEARCH_AUTO_REFRESH_DELAY); @@ -101,12 +100,13 @@ export function useMessageQuery({ messageId, pause }: { messageId: string; pause const isMessageFound = messageList.length > 0; const message = isMessageFound ? messageList[0] : null; const msgStatus = message?.status; + const isDelivered = isMessageFound && msgStatus === MessageStatus.Delivered; // Setup interval to re-query const reExecutor = useCallback(() => { - if (pause || (isMessageFound && msgStatus === MessageStatus.Delivered)) return; + if (pause || isDelivered || !isWindowVisible()) return; reexecuteQuery({ requestPolicy: 'network-only' }); - }, [pause, isMessageFound, msgStatus, reexecuteQuery]); + }, [pause, isDelivered, reexecuteQuery]); useInterval(reExecutor, MSG_AUTO_REFRESH_DELAY); return { @@ -117,3 +117,7 @@ export function useMessageQuery({ messageId, pause }: { messageId: string; pause message, }; } + +function isWindowVisible() { + return document.visibilityState === 'visible'; +}