@@ -2,33 +2,34 @@ import { useQuery, useApolloClient } from '@apollo/client'
2
2
import { SSR } from '../lib/constants'
3
3
import { GET_NEW_COMMENTS , COMMENT_WITH_NEW } from '../fragments/comments'
4
4
import { ITEM_FULL } from '../fragments/items'
5
- import { useCallback , useEffect , useState } from 'react'
5
+ import { useCallback , useEffect , useRef , useState } from 'react'
6
6
import styles from './comment.module.css'
7
7
8
8
const POLL_INTERVAL = 1000 * 10 // 10 seconds
9
9
10
10
export default function useLiveComments ( rootId , after , sort ) {
11
11
const client = useApolloClient ( )
12
12
const [ latest , setLatest ] = useState ( after )
13
- const [ queue , setQueue ] = useState ( [ ] )
13
+ const queue = useRef ( [ ] )
14
14
15
15
const { data } = useQuery ( GET_NEW_COMMENTS , SSR
16
16
? { }
17
17
: {
18
18
pollInterval : POLL_INTERVAL ,
19
- variables : { rootId, after : latest }
19
+ variables : { rootId, after : latest } ,
20
+ nextFetchPolicy : 'cache-and-network'
20
21
} )
21
22
22
23
useEffect ( ( ) => {
23
24
if ( ! data ?. newComments ) return
24
25
25
26
// live comments can be orphans if the parent comment is not in the cache
26
27
// 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 ]
28
29
const { queuedComments } = cacheNewComments ( client , rootId , allComments , sort )
29
30
30
31
// keep the queued comments for the next poll
31
- setQueue ( queuedComments )
32
+ queue . current = queuedComments
32
33
33
34
// update latest timestamp to the latest comment created at
34
35
setLatest ( prevLatest => getLatestCommentCreatedAt ( data . newComments . comments , prevLatest ) )
@@ -126,11 +127,15 @@ export function ShowNewComments ({ newComments = [], itemId, topLevel = false, s
126
127
const showNewComments = useCallback ( ( ) => {
127
128
const payload = ( data ) => {
128
129
// 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
+
134
139
return {
135
140
...data ,
136
141
comments : { ...data . comments , comments : dedupeComments ( data . comments . comments , freshNewComments ) } ,
0 commit comments