I've been working on a blog website and I'm trying to display users' comments on a blog post below that post (i.e. the comment section). On the click of a button, a fetch request is fired and it gets users' comments on that blog from a database in form of an array. On the frontend, I used then...catch
, to handle the results coming in. Using a forEach
loop to cycle through elements of the array, I first displayed them on the console and then tried displaying them on the comments section of the webpage using innerHTML
. Now on the console, all the elements are displayed but on the comments section only the last element shows up. Here is my code below:
// fetch and display comments
const viewCommentBtn = document.querySelector('a.view-comments');
const commentSection = document.getElementById('comments');
const commentSectionAddClass = document.querySelector('comments');
viewCommentBtn.addEventListener('click', (e) => {
const endpoint4 = `/blogs/${viewCommentBtn.dataset.doc}/view-comments`;
fetch(endpoint4)
.then(response => response.json())
.then(data => {
const comments = data.comments;
if (comments.length > 0){
comments.forEach(comment => {
console.log(comment.comment);
commentSection.innerHTML = `<div>${comment.user_id} says: <br> ${comment.comment}</div>`;
})
}
})
});
<a class="view-comments btn btn-primary" data-doc="<%= blog._id %>">view all comments ▿</a>
<div class="comments mt-5 px-3 py-2" id="comments">
</div>
Please do note that the elements of the array are actually objects containing properties that have to do with the details of the user's comment, e.g user's id, the blog's id, e.t.c. I realise this question might have been asked quite a number of times but the problems and solutions don't seem to match mine. I want to be able to display all the elements of the array on the comments section not only on the console. Thanks a lot in advance :)