Hook for adding and deleting comments on posts. Handles validation, state updates, and post comment count synchronization.
Parameters:
The post object to manage comments for
Returns:
Async function to add a new comment to the post The comment content to add
State setter function to clear the input after submission
Function to delete a comment with confirmation dialog The ID of the comment to delete
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:
Validates the comment content using CreateCommentSchema
Executes the comment creation via the API
Adds the comment to the local state
Updates the post’s commentCount
Clears the input field via setComment("")
const { handleAddComment } = useComment ({ post });
await handleAddComment ({
comment: "Great match!" ,
setComment
});
Deleting Comments:
The handleDeleteComment function:
Shows a native confirmation dialog
Executes the deletion if confirmed
Removes the comment from local state
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