I want to count the post view on a page of my Nuxt app when user scroll to it .
I have a list of posts on a page and I am using Intersection Observer to count Post views. When a user scrolls to a Post up/down that post view count must be increased by 1. I am using Nuxt js here. Not sure whether my procedure is correct or not because it increases the number of counts by 10, as it’s on the foreach loop and posts loaded 10 per page (Maybe taking the loop count).
I just want, if the user views (focus ) on a post scrolling up or down, just increase the post view count by 1 .
Here is what I did.
mounted() {
this.postScroll();
}
.......
methods () {
const posts = document.querySelectorAll(".postBody"); // Sélectionner toutes les vidéos
// currently fetching 10 posts per page as the setting is set to 10
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
entry.target.classList.toggle('visible', entry.isIntersecting)
if(entry.isIntersecting && entry.target.classList.contains('visible')){
// get post id from postBody
const postId = entry.target.getAttribute("id")
//Here I am calling the server and there increased the count by current view +1
try{
axios.post(`${this.$config.apiBaseURL}/api/posts/${postId}/view`)
.then(res => {
console.log(res)
})
}catch(error){
console.log("An error occcured , Please try again later.")
}
observer.unobserve(entry.target);
}
})
}, {threshold: 1});
posts.forEach((post) => {
observer.observe(post);
});
}
I am not sure whether to attach a scroll or focus event or not.
But I think I am doing something wrong on the whole process When scrolling it increased the view count by 10, but If I scroll to a post on the page view count should be increased by 1.
In general If I scroll to a post, the view count should be counted by 1.