'How to stop displaying same posts
From the code below I am able to view my liked posts, if I press the like button of the post. But the issue is every time when I press the button to see the liked posts it's creating another same post. by the isLiked function I can like posts with heart expression and this liked post stored and when I press the like button this post appears which I liked this post but if I press the like button again its showing another same post with the previous post. so my question is how can I set the display function to get rid of this issue.
Here is the code
enter code here let posts = [];
const likedPostsId = [];
const getLikedPosts = () => {
return posts.filter((post) => likedPostsId.includes(post.id));
};
const isLiked = (id) => {
return likedPostsId?.length && likedPostsId.includes(id);
};
const addToLiked = (id) => {
likedPostsId.push(id);
showPosts(posts);
};
const switchTab = (id) => {
if (id === "liked") {
document.getElementById("liked").style.display = "block";
displayLikedPosts();
}
};
const createPost = (post) => {
const image = post.userImage;
const image1 = post.image;
const comments = post.comments;
const div = document.createElement("article");
div.classList.add("post");
div.innerHTML = `
<div class="post__header">
<div class="post__profile">
<a
href="https://github.com/ProgrammingHero1"
target="_blank"
class="post__avatar"
>
<img src="${image}" alt="User Picture" />
</a>
<a href="#" class="post__user">phero</a>
</div>
<button class="post__more-options">
<i class="fa-solid fa-ellipsis"></i>
</button>
</div>
<div class="post__content">
<div class="post__medias">
<img
class="post__media"
src="${image1}"
alt="Post Content"
/>
</div>
</div>
<div class="post__footer">
<div class="post__buttons">
<button class="post__button"
onclick="addToLiked(${post.id})">
<i class="fa-solid fa-heart ${isLiked(post.id) &&
"text-danger"}"></i>
`;
return div;
};
const displayLikedPosts = () => {
const likedPosts = getLikedPosts();
likedPosts.forEach((post) => {
const div = createPost(post);
document.getElementById("liked").appendChild(div);
});
};
<ul class="navbar-nav mr-auto">
<li class="nav-link active" role="button"
onclick="switchTab( 'posts' )">
<i class="fa-solid fa-house"></i>
</li>
<li class="nav-link active" role="button"
onclick="switchTab( 'liked' )">
<i class="fa-solid fa-heart text-danger"></i>
</li>
<li class="nav-link active" role="button"
onclick="switchTab( 'reported' )">
<i class="fa-solid fa-eye-slash"></i>
</li>
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
