@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
68 lines • 2.43 kB
JavaScript
import { useEffect, useState } from "react";
import { handleError } from "../../utils/handleError";
import useCommentSection from "./useCommentSection";
import useFetchManyComments from "./useFetchManyComments";
import { isUUID } from "../../utils/isUUID";
function useReplies({ commentId, sortBy }) {
const fetchManyComments = useFetchManyComments();
const { addCommentsToTree, entityCommentsTree } = useCommentSection();
const [page, setPage] = useState(0);
const [loadingState, setLoadingState] = useState(false);
const commentData = entityCommentsTree[commentId];
if (!commentData) {
return {
replies: [],
newReplies: [],
loading: loadingState,
page,
setPage,
}; // If the commentID is not found, return an empty array
}
const allReplies = commentData.replies;
const replies = Object.values(allReplies).filter((reply) => !reply.new);
const newReplies = Object.values(allReplies)
.filter((reply) => !!reply.new)
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
useEffect(() => {
const loadReplies = async () => {
if (!commentId || !isUUID(commentId)) {
// console.warn(
// "The 'fetch comments' operation was invoked without a valid comment ID and has been aborted."
// );
return;
}
try {
setLoadingState(true);
const response = await fetchManyComments({
parentId: commentId,
page,
sortBy,
limit: 5,
include: "user", // Always include user for replies display
});
if (response) {
const { data: fetchedReplies } = response;
addCommentsToTree?.(fetchedReplies);
}
}
catch (err) {
handleError(err, "Failed to fetch replies: ");
}
finally {
setLoadingState(false);
}
};
if (page > 0) {
loadReplies();
}
}, [page]);
return {
replies,
newReplies,
loading: loadingState,
page,
setPage,
};
}
export default useReplies;
//# sourceMappingURL=useReplies.js.map