fix: prevent GET_NEW_COMMENTS query from running in-between renders (#2345)

This commit is contained in:
soxa 2025-07-30 19:35:38 +02:00 committed by GitHub
parent d175d0e64d
commit 1aeb206842
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -42,15 +42,25 @@ function cacheNewComments (client, rootId, newComments, sort) {
export default function useLiveComments (rootId, after, sort) { export default function useLiveComments (rootId, after, sort) {
const latestKey = `liveCommentsLatest:${rootId}` const latestKey = `liveCommentsLatest:${rootId}`
const client = useApolloClient() const client = useApolloClient()
const [latest, setLatest] = useState(() => { const [latest, setLatest] = useState(after)
// if we're on the client, get the latest timestamp from session storage, otherwise use the passed after timestamp const [initialized, setInitialized] = useState(false)
if (typeof window !== 'undefined') {
return window.sessionStorage.getItem(latestKey) || after
}
return after
})
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, pollInterval: POLL_INTERVAL,