fix(use-replies.ts): flatten comment pages

This commit is contained in:
plebeius.eth
2024-04-02 16:42:36 +02:00
parent 77eaf9ede7
commit 087d4ab738
+6 -4
View File
@@ -1,27 +1,29 @@
import { useMemo, useCallback } from 'react';
import { Comment, useAccountComments } from '@plebbit/plebbit-react-hooks';
import { flattenCommentsPages } from '@plebbit/plebbit-react-hooks/dist/lib/utils';
const useRepliesAndAccountReplies = (comment: Comment) => {
// filter only the parent cid
const filter = useCallback((accountComment: Comment) => accountComment.parentCid === (comment?.cid || 'n/a'), [comment?.cid]);
const { accountComments } = useAccountComments({ filter });
const flattenedReplies = useMemo(() => flattenCommentsPages(comment.replies), [comment.replies]);
// the account's replies have a delay before getting published, so get them locally from accountComments instead
const accountRepliesNotYetPublished = useMemo(() => {
const replies = comment?.replies?.pages?.topAll?.comments || [];
const replies = flattenedReplies || [];
const replyCids = new Set(replies.map((reply: Comment) => reply?.cid));
// filter out the account comments already in comment.replies, so they don't appear twice
return accountComments.filter((accountReply) => !replyCids.has(accountReply?.cid));
}, [comment?.replies?.pages?.topAll?.comments, accountComments]);
}, [flattenedReplies, accountComments]);
const repliesAndNotYetPublishedReplies = useMemo(() => {
return [
// put the author's unpublished replies at the top, latest first (reverse)
...accountRepliesNotYetPublished.reverse(),
// put the published replies after,
...(comment?.replies?.pages?.topAll?.comments || []),
...(flattenedReplies || []),
];
}, [comment?.replies?.pages?.topAll?.comments, accountRepliesNotYetPublished]);
}, [flattenedReplies, accountRepliesNotYetPublished]);
return repliesAndNotYetPublishedReplies;
};