How do I make it so it does not just like the newest post and it will like the post that they clicked the like button on?
code:
postSearch.addEventListener("input", (ev) => {
async function findPosts() {
const postsRef = collection(firestore, "posts")
const q = query(postsRef, orderBy("createdAt"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((post) => {
// doc.data() is never undefined for query doc snapshots
if (post.data().likes == undefined) {
post.data().likes = 0
}
function epicTest() {
let postData = {
description: post.data().description,
display_name: post.data().display_name,
createdAt: post.data().createdAt,
uid: post.data().uid,
title: post.data().title,
likes: post.data().likes 1
}
console.log(post.id)
console.log(postData)
setDoc(doc(postsRef, post.id), postData)
console.log("this feature hasn't been added yet")
}
let items = querySnapshot.docs.map(post => {
if (post.data().title.includes(ev.target.value) || post.data().description.includes(ev.target.value)) {
return `<div id="postBox">
<h4 id="postName">${post.data().display_name}</h4>
<h1 id="postTitle">${post.data().title}</h1>
<h3 id="postDescription">${post.data().description}</h3>
<div id="likeContainer"><ion-icon name="thumbs-up-outline" id="likeBtn" onclick="epicTest()"></ion-icon><h3 id="likeCount">${post.data().likes}</h3></div>
</div>`
}
});
items.reverse()
postList.innerHTML = items.join('');
if (postList.innerText == "") {
postList.innerText = "no results found"
}
let likeBtn = document.querySelectorAll("#likeBtn")
likeBtn.forEach(item => {
item.addEventListener("click", (ev) => {
let postData = {
description: post.data().description,
display_name: post.data().display_name,
createdAt: post.data().createdAt,
uid: post.data().uid,
title: post.data().title,
likes: post.data().likes 1
}
console.log(post.id)
console.log(postData)
setDoc(doc(postsRef, post.id), postData)
console.log("this feature hasn't been added yet")
})
})
});
}
findPosts()
})
CodePudding user response:
The following example shows how you can use the function to run whenever a 'Like' button is clicked, check the below sample:
var postRef = new Firebase(firebaseURL id);
postRef.child('like-count').once('value', function(snapshot) {
var currentLikes = snapshot.val() ? snapshot.val() : 0;
postRef.update({
'postID': id,
'like-count': currentLikes 1
}, function(error) {
if (error) {
console.log('Data could not be saved:' error);
} else {
console.log('Data saved successfully');
}
});
getLikeCount(id);
});
}
The basic idea behind this is to pass the post id as a parameter to the function that is called when clicking the like button.
Also check the following examples for similar implementations: