From 1aeb2068422bae1509ffa670efa4235fe57fef3e Mon Sep 17 00:00:00 2001 From: soxa <6390896+Soxasora@users.noreply.github.com> Date: Wed, 30 Jul 2025 19:35:38 +0200 Subject: [PATCH] fix: prevent GET_NEW_COMMENTS query from running in-between renders (#2345) --- components/use-live-comments.js | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/components/use-live-comments.js b/components/use-live-comments.js index d85f3fc2..0f401312 100644 --- a/components/use-live-comments.js +++ b/components/use-live-comments.js @@ -42,15 +42,25 @@ function cacheNewComments (client, rootId, newComments, sort) { export default function useLiveComments (rootId, after, sort) { const latestKey = `liveCommentsLatest:${rootId}` const client = useApolloClient() - const [latest, setLatest] = useState(() => { - // if we're on the client, get the latest timestamp from session storage, otherwise use the passed after timestamp - if (typeof window !== 'undefined') { - return window.sessionStorage.getItem(latestKey) || after - } - return after - }) + const [latest, setLatest] = useState(after) + const [initialized, setInitialized] = useState(false) - const { data } = useQuery(GET_NEW_COMMENTS, SSR + useEffect(() => { + if (typeof window !== 'undefined') { + const storedLatest = window.sessionStorage.getItem(latestKey) + if (storedLatest && storedLatest > after) { + setLatest(storedLatest) + } else { + setLatest(after) + } + } + + // Apollo might update the cache before the page has fully rendered, causing reads of stale cached data + // this prevents GET_NEW_COMMENTS from producing results before the page has fully rendered + setInitialized(true) + }, [after]) + + const { data } = useQuery(GET_NEW_COMMENTS, SSR || !initialized ? {} : { pollInterval: POLL_INTERVAL,