toggleCommentLike method

Future<void> toggleCommentLike(
  1. String commentId
)

Implementation

Future<void> toggleCommentLike(String commentId) async {
  final token = Hive.box('user_data').get('user_token');
  if (token == null) {
    Get.snackbar('Error', 'Please login to like comments');
    return;
  }

  try {
    final response = await _apiService.post(
      endpoint: '${CommunityConstants.comments}/$commentId/like',
      headers: {
        'api-key': CommunityConstants.apiKey,
        'Authorization': 'Bearer $token',
        'Accept': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      // Update the comment in the list
      if (comments.value != null) {
        final commentIndex = comments.value!.data.indexWhere(
          (c) => c.id.toString() == commentId,
        );
        if (commentIndex != -1) {
          final updatedComment = comments.value!.data[commentIndex];
          final wasLiked = updatedComment.isLikedByUser ?? false;
          comments.value!.data[commentIndex] = Comment(
            id: updatedComment.id,
            content: updatedComment.content,
            postId: updatedComment.postId,
            parentId: updatedComment.parentId,
            replies: updatedComment.replies,
            likesCount: wasLiked
                ? updatedComment.likesCount - 1
                : updatedComment.likesCount + 1,
            user: updatedComment.user,
            isLikedByUser: !wasLiked,
            createdAt: updatedComment.createdAt,
            updatedAt: updatedComment.updatedAt,
          );
          comments.refresh();
        }
      }
    } else {
      Get.snackbar('Error', 'Failed to like comment');
    }
  } catch (e) {
    Get.snackbar('Error', 'Failed to like comment: ${e.toString()}');
  }
}