Skip to main content

useComment

Hook for adding and deleting comments on posts. Handles validation, state updates, and post comment count synchronization. Parameters:
post
Post
required
The post object to manage comments for
Returns:
handleAddComment
function
Async function to add a new comment to the post
handleDeleteComment
function
Function to delete a comment with confirmation dialog
Usage Example:
import useComment from '@/hooks/useComment';
import { Post } from '@/schemas/PostSchema';

function PostDetails({ post }: { post: Post }) {
  const [comment, setComment] = useState<string>("");
  const { handleAddComment, handleDeleteComment } = useComment({ post });

  return (
    <View>
      {/* Comment Input */}
      <TextInput
        value={comment}
        onChangeText={setComment}
        placeholder="Comment"
      />
      
      <Pressable
        onPress={() => handleAddComment({ comment, setComment })}
      >
        <Ionicons name="send-outline" size={18} color="white" />
      </Pressable>

      {/* Comment List */}
      {commentList.map((item) => (
        <CommentCard
          key={item.$id}
          comment={item}
          onDeletePress={() => handleDeleteComment(item.$id)}
        />
      ))}
    </View>
  );
}
Adding Comments: The handleAddComment function:
  1. Validates the comment content using CreateCommentSchema
  2. Executes the comment creation via the API
  3. Adds the comment to the local state
  4. Updates the post’s commentCount
  5. Clears the input field via setComment("")
const { handleAddComment } = useComment({ post });

await handleAddComment({ 
  comment: "Great match!", 
  setComment 
});
Deleting Comments: The handleDeleteComment function:
  1. Shows a native confirmation dialog
  2. Executes the deletion if confirmed
  3. Removes the comment from local state
  4. Decrements the post’s commentCount
const { handleDeleteComment } = useComment({ post });

handleDeleteComment("comment-id-123");
// Shows: "Are you sure? Do you want to delete this comment?"
Validation: Comments are validated using CreateCommentSchema which checks:
  • Content is not empty
  • Content meets length requirements
  • Valid postId is provided
Error Handling: The hook displays appropriate error toasts:
  • Validation errors: Displays the schema validation message
  • Add failed: “Could not add comment. Please try again later.”
  • Delete failed: “Could not delete comment. Please try again later.”
State Synchronization: The hook automatically synchronizes multiple state stores:
  • Updates useComments store for the comment list
  • Updates usePosts store for the post’s commentCount
  • Calls the updatePost service to persist changes
Source: /workspace/source/hooks/useComment.ts:10

Build docs developers (and LLMs) love