Skip to content

Commit e7ac94d

Browse files
committed
enhance: store ids of new comments in the cache, instead of carrying full comments that would get discarded anyway
1 parent 0c2d6f8 commit e7ac94d

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

components/show-new-comments.js

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,20 @@ import { itemUpdateQuery, commentUpdateFragment } from './use-live-comments'
66

77
function prepareComments (client, newComments) {
88
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 => {
1412
const fragment = client.cache.readFragment({
15-
id: `Item:${c.id}`,
13+
id: `Item:${id}`,
1614
fragment: COMMENT_WITH_NEW,
1715
fragmentName: 'CommentWithNew'
1816
})
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
2123
})
2224

2325
// count the total number of comments including nested comments
@@ -40,10 +42,12 @@ export function ShowNewComments ({ topLevel = false, comments, newComments = [],
4042
const client = useApolloClient()
4143

4244
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))
4447
}, [newComments, comments])
4548

4649
const showNewComments = useCallback(() => {
50+
// fetch the latest version of the comments from the cache by their ids
4751
const payload = prepareComments(client, dedupedNewComments)
4852

4953
if (topLevel) {

components/use-live-comments.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ function mergeNewComment (item, newComment) {
114114
return item
115115
}
116116

117-
return { ...item, newComments: [...existingNewComments, newComment] }
117+
return { ...item, newComments: [...existingNewComments, newComment.id] }
118118
}
119119

120120
function getLatestCommentCreatedAt (comments, latest) {

0 commit comments

Comments
 (0)