Skip to content

Commit 6a93d2a

Browse files
committed
enhance: queuedComments Ref, cache-and-network fetch policy; freshNewComments readFragment fallback to received comment
1 parent d15a024 commit 6a93d2a

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

components/use-live-comments.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,33 +2,34 @@ import { useQuery, useApolloClient } from '@apollo/client'
22
import { SSR } from '../lib/constants'
33
import { GET_NEW_COMMENTS, COMMENT_WITH_NEW } from '../fragments/comments'
44
import { ITEM_FULL } from '../fragments/items'
5-
import { useCallback, useEffect, useState } from 'react'
5+
import { useCallback, useEffect, useRef, useState } from 'react'
66
import styles from './comment.module.css'
77

88
const POLL_INTERVAL = 1000 * 10 // 10 seconds
99

1010
export default function useLiveComments (rootId, after, sort) {
1111
const client = useApolloClient()
1212
const [latest, setLatest] = useState(after)
13-
const [queue, setQueue] = useState([])
13+
const queue = useRef([])
1414

1515
const { data } = useQuery(GET_NEW_COMMENTS, SSR
1616
? {}
1717
: {
1818
pollInterval: POLL_INTERVAL,
19-
variables: { rootId, after: latest }
19+
variables: { rootId, after: latest },
20+
nextFetchPolicy: 'cache-and-network'
2021
})
2122

2223
useEffect(() => {
2324
if (!data?.newComments) return
2425

2526
// live comments can be orphans if the parent comment is not in the cache
2627
// queue them up and retry later, when the parent decides they want the children.
27-
const allComments = [...queue, ...data.newComments.comments]
28+
const allComments = [...queue.current, ...data.newComments.comments]
2829
const { queuedComments } = cacheNewComments(client, rootId, allComments, sort)
2930

3031
// keep the queued comments for the next poll
31-
setQueue(queuedComments)
32+
queue.current = queuedComments
3233

3334
// update latest timestamp to the latest comment created at
3435
setLatest(prevLatest => getLatestCommentCreatedAt(data.newComments.comments, prevLatest))
@@ -126,11 +127,15 @@ export function ShowNewComments ({ newComments = [], itemId, topLevel = false, s
126127
const showNewComments = useCallback(() => {
127128
const payload = (data) => {
128129
// fresh newComments
129-
const freshNewComments = newComments.map(c => client.cache.readFragment({
130-
id: `Item:${c.id}`,
131-
fragment: COMMENT_WITH_NEW,
132-
fragmentName: 'CommentWithNew'
133-
}))
130+
const freshNewComments = newComments.map(c => {
131+
const fragment = client.cache.readFragment({
132+
id: `Item:${c.id}`,
133+
fragment: COMMENT_WITH_NEW,
134+
fragmentName: 'CommentWithNew'
135+
})
136+
return fragment || c
137+
})
138+
134139
return {
135140
...data,
136141
comments: { ...data.comments, comments: dedupeComments(data.comments.comments, freshNewComments) },

0 commit comments

Comments
 (0)