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/referenceId/shortId/entity):

ParameterTypeRequiredDescription
entityIdstring | undefined | nullNoThe ID of the entity in Replyke’s system.
referenceIdstring | 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.
entitystring | 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
entityIdstring | undefined | nullThe ID of the associated entity.
callbacksSocialStyleCallbacksThe callbacks passed into the hook.
entityCommentsTreeEntityCommentsTreeThe tree structure of the comments associated with the entity.
commentsCommentType[]The list of root-level comments fetched so far.
newCommentsCommentType[]Newly added root-level comments.
loadingbooleanIndicates whether comments are being loaded.
hasMorebooleanIndicates whether there are more comments to fetch.
submittingCommentbooleanIndicates whether a comment is currently being submitted.
loadMore() => voidA function to fetch the next page of comments.
sortByCommentsSortByOptions | nullThe current sorting criteria for comments.
setSortBy(newSortBy: CommentsSortByOptions) => voidA function to update the sorting criteria.
pushMentionUserLean | nullThe user being mentioned in a reply.
setPushMention(user: UserLean | null) => voidA function to set the user being mentioned.
previousPushMentionUserLean | nullThe previously mentioned user.
selectedCommentCommentType | nullThe currently selected comment.
setSelectedComment(newSelectedComment: CommentType | null) => voidA function to set the selected comment.
repliedToCommentPartial<CommentType> | nullThe comment being replied to.
setRepliedToComment(newRepliedToComment: CommentType | null) => voidA function to set the replied-to comment.
showReplyBannerbooleanIndicates whether the reply banner is shown.
setShowReplyBanner(newState: boolean) => voidA function to toggle the reply banner.
addCommentsToTree(newComments: CommentType[], newlyAdded?: boolean) => voidA function to add comments to the tree structure.
removeCommentFromTree(commentId: string) => voidA function to remove a comment from the tree structure.
createComment(props: { content: string; mentions: Mention[] }) => Promise<void>A function to create a new comment.
updateComment(props: { commentId: string; content: string }) => Promise<void>A function to update an existing comment.
deleteComment(props: { commentId: string }) => Promise<void>A function to delete a comment.
highlightedComment{ comment: CommentType; parentComment: CommentType | null } | nullThe highlighted comment and its parent (if any).