How to prevent like icon class from changing to regular after reloading page?

14 Views Asked by At

I have a like button for a post. The like count is incremented in the database when the user likes the post, and the like icon class is changed to solid. However, when the user reloads the page, the like icon class changes to regular, even though the like count is still correct in the database.

I am using the following code for the like button:

<div class="like-container">
  <i
    class="fa-thumbs-up {% if post.liked_by_user %}fa-solid fa-xs{% else %}fa-regular fa-xs{% endif %} like-icon"
    id="like-icon-{{ post.id }}"
    data-post-id="{{ post.id }}"
    data-liked="{{ post.liked_by_user }}"
    onclick="handleLikeClick(this)"
  ></i>
  <span class="like-count">{{ post.count_likes() }} </span><b id="txt"> Likes</b>
</div>

HERE IS AJAX CODE

function handleLikeClick(likeIcon) {
  const postID = likeIcon.getAttribute('data-post-id');
  const liked = likeIcon.getAttribute('data-liked') === 'true';

  $.ajax({
    url: '/like_post',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ post_id: postID }),
    success: function (response) {
      // Update the like count and icon class based on the response
      const likeCountSpan = $(likeIcon).siblings('.like-count');
      likeCountSpan.text(response.like_count);
      if (response.liked_by_user) {
        $(likeIcon).removeClass('fa-regular').addClass('fa-solid');
      } else {
        $(likeIcon).removeClass('fa-solid').addClass('fa-regular');
      }

      // Update the data-liked attribute
      likeIcon.setAttribute('data-liked', response.liked_by_user);
    },
    error: function (error) {
      console.error('Error:', error);
    }
  });
}

python flask route

@app.route('/like_post', methods=['POST'])
@login_required  # Use the appropriate decorator for user authentication
def like_post():
    post_id = request.json['post_id']
    post = Post.query.get_or_404(post_id)
    existing_like = Like.query.filter_by(user=current_user, post=post).first()
    liked_by_user = existing_like is not None

    if not post:
        flash("Post does not exist", "error")
        return jsonify({'error': 'Post does not exist'})

    if existing_like:
        # User has already liked the post, so unlike it
        db.session.delete(existing_like)
        db.session.commit()
        liked_by_user = False
    else:
        # User has not liked the post, so like it
        like = Like(user=current_user, post=post)
        db.session.add(like)
        db.session.commit()
        liked_by_user = True
    
    response_data = {
        'liked_by_user': liked_by_user,
        'like_count': post.count_likes()  # Assuming you have a method to count likes
    }

    return jsonify(response_data)

I want to show the user the state of like, either he liked the post or not, even after reloading the page, the icon class should not be changed. But now if user likes the post, count is incrementing as required and class changes smoothly but if user reload the page the class changes from solid to regular but count is fine.

How to fix that? Will be very thankful for guidance..

0

There are 0 best solutions below