@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
73 lines • 2.8 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const handleError_1 = require("../../utils/handleError");
const useCommentSection_1 = __importDefault(require("./useCommentSection"));
const useFetchManyComments_1 = __importDefault(require("./useFetchManyComments"));
const isUUID_1 = require("../../utils/isUUID");
function useReplies({ commentId, sortBy }) {
const fetchManyComments = (0, useFetchManyComments_1.default)();
const { addCommentsToTree, entityCommentsTree } = (0, useCommentSection_1.default)();
const [page, setPage] = (0, react_1.useState)(0);
const [loadingState, setLoadingState] = (0, react_1.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());
(0, react_1.useEffect)(() => {
const loadReplies = async () => {
if (!commentId || !(0, isUUID_1.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) {
(0, handleError_1.handleError)(err, "Failed to fetch replies: ");
}
finally {
setLoadingState(false);
}
};
if (page > 0) {
loadReplies();
}
}, [page]);
return {
replies,
newReplies,
loading: loadingState,
page,
setPage,
};
}
exports.default = useReplies;
//# sourceMappingURL=useReplies.js.map