@replyke/core
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
100 lines • 3.79 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 useFetchCommentReactions_1 = __importDefault(require("./useFetchCommentReactions"));
const handleError_1 = require("../../utils/handleError");
function useFetchCommentReactionsWrapper(props) {
const { commentId, limit = 20, reactionType, sortDir = "desc", autoFetch = false, } = props;
const fetchCommentReactions = (0, useFetchCommentReactions_1.default)();
const loading = (0, react_1.useRef)(false);
const [loadingState, setLoadingState] = (0, react_1.useState)(false);
const hasMore = (0, react_1.useRef)(true);
const [hasMoreState, setHasMoreState] = (0, react_1.useState)(true);
const [page, setPage] = (0, react_1.useState)(1);
const [reactions, setReactions] = (0, react_1.useState)([]);
const resetReactions = (0, react_1.useCallback)(async () => {
if (!commentId) {
return;
}
try {
loading.current = true;
setLoadingState(true);
hasMore.current = true;
setHasMoreState(true);
setPage(1);
const response = await fetchCommentReactions({
commentId,
page: 1,
limit,
reactionType,
sortDir,
});
if (response) {
const { data: newReactions, pagination } = response;
setReactions(newReactions);
hasMore.current = pagination.hasMore;
setHasMoreState(pagination.hasMore);
}
}
catch (err) {
(0, handleError_1.handleError)(err, "Failed to reset reactions:");
}
finally {
loading.current = false;
setLoadingState(false);
}
}, [fetchCommentReactions, limit, reactionType, sortDir, commentId]);
const loadMore = () => {
if (loading.current || !hasMore.current)
return;
setPage((prevPage) => prevPage + 1);
};
(0, react_1.useEffect)(() => {
if (autoFetch) {
resetReactions();
}
}, [resetReactions, autoFetch]);
(0, react_1.useEffect)(() => {
const loadMoreReactions = async () => {
loading.current = true;
setLoadingState(true);
try {
const response = await fetchCommentReactions({
commentId,
page,
limit,
reactionType,
sortDir,
});
if (response) {
const { data: newReactions, pagination } = response;
setReactions((prevReactions) => [...prevReactions, ...newReactions]);
hasMore.current = pagination.hasMore;
setHasMoreState(pagination.hasMore);
}
}
catch (err) {
(0, handleError_1.handleError)(err, "Loading more reactions failed:");
}
finally {
loading.current = false;
setLoadingState(false);
}
};
if (page > 1 && hasMore.current && !loading.current) {
loadMoreReactions();
}
}, [page, fetchCommentReactions, commentId, limit, reactionType, sortDir]);
return {
reactions,
loading: loadingState,
hasMore: hasMoreState,
loadMore,
refetch: resetReactions,
};
}
exports.default = useFetchCommentReactionsWrapper;
//# sourceMappingURL=useFetchCommentReactionsWrapper.js.map