@@ -6,18 +6,20 @@ import { itemUpdateQuery, commentUpdateFragment } from './use-live-comments'
6
6
7
7
function prepareComments ( client , newComments ) {
8
8
return ( data ) => {
9
- // TODO: it might be sane to pass the cache ref to the ShowNewComments component
10
- // TODO: and use it to read the latest newComments from the cache
11
- // newComments can have themselves new comments between the time the button is clicked and the query is executed
12
- // so we need to read the latest newComments from the cache
13
- const freshNewComments = newComments . map ( c => {
9
+ // newComments is an array of comment ids that allows us
10
+ // to read the latest newComments from the cache, guaranteeing that we're not reading stale data
11
+ const freshNewComments = newComments . map ( id => {
14
12
const fragment = client . cache . readFragment ( {
15
- id : `Item:${ c . id } ` ,
13
+ id : `Item:${ id } ` ,
16
14
fragment : COMMENT_WITH_NEW ,
17
15
fragmentName : 'CommentWithNew'
18
16
} )
19
- // if the comment is not in the cache, return the original comment
20
- return fragment || c
17
+
18
+ if ( ! fragment ) {
19
+ return null
20
+ }
21
+
22
+ return fragment
21
23
} )
22
24
23
25
// count the total number of comments including nested comments
@@ -40,10 +42,12 @@ export function ShowNewComments ({ topLevel = false, comments, newComments = [],
40
42
const client = useApolloClient ( )
41
43
42
44
const dedupedNewComments = useMemo ( ( ) => {
43
- return newComments . filter ( c => ! comments . some ( cc => cc . id === c . id ) )
45
+ const existingIds = new Set ( comments . map ( c => c . id ) )
46
+ return newComments . filter ( id => ! existingIds . has ( id ) )
44
47
} , [ newComments , comments ] )
45
48
46
49
const showNewComments = useCallback ( ( ) => {
50
+ // fetch the latest version of the comments from the cache by their ids
47
51
const payload = prepareComments ( client , dedupedNewComments )
48
52
49
53
if ( topLevel ) {
0 commit comments