In the displayLikedPosts there is a function called getLikedPosts. this getLikedPosts function filter the posts ID and insert posts into an array. Now after running forEach loop inside the displayLikedPosts ---first time it adds a new and single post(ex:post-1) but second time it displays the previous post twice and the new post (ex: post-1,post-1,newpost). But my purpose is to display only the previous one and the new posts(ex:post-1,newpost,newpost2,newpost4)
code
const displayLikedPosts = () => {
const likedPosts = getLikedPosts();
likedPosts.forEach((post) => {
const div = createPost(post);
document.getElementById("liked").appendChild(div);
});
};
CodePudding user response:
Clear thr content inside #liked
before appending new elements
Pseudo Code
const displayLikedPosts = () => {
const likedPosts = getLikedPosts();
document.getElementById("liked")innerHTML = "";
likedPosts.forEach((post) => {
const div = createPost(post);
document.getElementById("liked").appendChild(div);
});
};
CodePudding user response:
You must first delete the children of your parent DOM node, then add the elements again. There are many ways to delete the children, which are discussed in this thread. You may find that some options are better (and/ or more modern) than others.
Here is a small minimal example for your use case using setInterval()
to prove that the list does not contain duplicates.
/**
* Display posts
* @param {string[]} posts posts to display
*/
function displayPosts(posts) {
const parent = document.getElementById("liked");
// delete children
deleteChildren(parent);
// add items to the list
posts.forEach((post) => {
const listItem = document.createElement("li");
listItem.textContent = post;
parent.appendChild(listItem);
});
console.log("rendered")
}
/**
* Deletes all children of a DOM node.
* @param {HTMLElement} parent parent element
*/
function deleteChildren(parent) {
while (parent.firstChild) {
parent.firstChild.remove();
}
}
window.addEventListener("DOMContentLoaded", (event) => {
// posts to display
const posts = ["post 1", "post 2", "post 3", "post 4"];
displayPosts(posts)
// call method every 3 seconds to demonstrate it works
setInterval(() => displayPosts(posts), 3 * 1000);
});
<ul id="liked">
</ul>