useCommentSectionData

Overview

The useCommentSectionData hook provides a comprehensive solution for managing comment sections associated with entities. Unlike individual hooks such as useFetchComments or useCreateComment, this hook combines functionalities like fetching, creating, updating, deleting, and managing comment states (e.g., sorting, replying). It is ideal for implementing fully-featured comment sections with advanced state management.

Usage Example

import { useCommentSectionData } from "@replyke/react-js";
 
function CommentSection({ entityId }: { entityId: string }) {
  const {
    comments,
    entityCommentsTree,
    loading,
    hasMore,
    sortBy,
    setSortBy,
    loadMore,
    createComment,
    updateComment,
    deleteComment,
    repliedToComment,
    setRepliedToComment,
    showReplyBanner,
    setShowReplyBanner,
  } = useCommentSectionData({ entityId, limit: 15 });
 
  const handleAddComment = async () => {
    try {
      await createComment({
        content: "This is a new comment!",
        mentions: [],
      });
    } catch (error) {
      console.error("Failed to add comment:", error.message);
    }
  };
 
  return (
    <div>
      <select
        value={sortBy}
        onChange={(e) => setSortBy(e.target.value as "new" | "top")}
      >
        <option value="new">Newest</option>
        <option value="top">Top</option>
      </select>
 
      <ul>
        {comments.map((comment) => (
          <li key={comment.id}>{comment.content}</li>
        ))}
      </ul>
 
      {loading && <p>Loading...</p>}
      {hasMore && !loading && (
        <button onClick={loadMore}>Load More</button>
      )}
 
      {showReplyBanner && <p>Replying to {repliedToComment?.id}</p>}
      <button onClick={handleAddComment}>Add Comment</button>
    </div>
  );
}

Parameters & Returns

Parameters

The hook accepts an object with the fields below. At least one of the first 4 fields must be provided (entityId/foreignId/shortId/entity):

ParameterTypeRequiredDescription
entityIdstring | undefined | nullNoThe ID of the entity in Replyke’s system.
foreignIdstring | undefined | nullNoThe original item’s ID if integrated with an external dataset, or a static value (e.g., “about-page”).
shortIdstring | undefined | nullNoThe unique short ID of the entity.
entityEntity | undefined | nullNoA complete Entity object.
createIfNotFoundstring | undefined | nullNoAn optional flag which instructs Replyke to create an entity if one isn’t found.
limitnumberNoThe number of comments to fetch per page. Default is 15.
defaultSortByCommentsSortByOptionsNoThe default sorting criteria for comments (e.g., new, top).
callbacksSocialStyleCallbacksNoOptional callbacks for handling events like login requirements.
highlightedCommentIdstring | nullNoThe ID of a comment to highlight (e.g., for linking or deep linking).

Returns

The hook returns an object with the following fields:

Return ValueTypeDescription
entityEntity | undefined | nullThe associated entity for the comment section.
callbacksRecord<string, (...args: any[]) => void> | undefinedOptional callbacks passed into the hook.
entityCommentsTreeEntityCommentsTreeTree structure representing threaded comments.
commentsComment[]The list of root-level comments currently loaded.
newCommentsComment[]Comments that were recently added during the session.
highlightedComment{ comment: Comment; parentComment: Comment | null } | nullA highlighted comment and its parent, useful for deep linking.
loadingbooleanIndicates if comments are currently loading.
hasMorebooleanWhether there are more comments available for pagination.
submittingCommentbooleanWhether a comment is currently being submitted.
loadMore() => voidLoads the next page of comments.
sortByCommentsSortByOptions | nullCurrent sorting method for the comments.
setSortBy(newSortBy: CommentsSortByOptions) => voidUpdates the comment sort order.
pushMentionUserLean | nullUser that is being mentioned in a reply.
selectedCommentComment | nullThe comment currently selected (e.g., for editing or context menu).
setSelectedComment(newSelectedComment: Comment | null) => voidSets the selected comment.
repliedToCommentPartial<Comment> | nullThe comment being replied to.
setRepliedToComment(newRepliedToComment: Comment | null) => voidSets the comment being replied to.
showReplyBannerbooleanWhether the UI banner indicating a reply is visible.
setShowReplyBanner(newState: boolean) => voidControls the reply banner visibility.
addCommentsToTree(newComments: Comment[] | undefined, newlyAdded?: boolean) => voidAdds comments to the threaded comment tree.
removeCommentFromTree(commentId: string) => voidRemoves a comment from the tree structure.
handleShallowReply(comment: Comment) => voidHandles a shallow reply (mention-only, not nested).
handleDeepReply(comment: Comment) => voidHandles a deep reply (visibly nested under the parent comment).
createComment(props: { content?: string; gif?: GifData; mentions: Mention[] }) => Promise<void>Submits a new comment. Includes temporary rendering and error fallback.
updateComment(props: { commentId: string; content: string }) => Promise<void>Updates an existing comment.
deleteComment(props: { commentId: string }) => Promise<void>Deletes a comment from both the UI and backend.