Home > Back-end >  My forEach loop displays only the last value
My forEach loop displays only the last value

Time:08-26

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  data-doc="<%= blog._id %>">view all comments &triangledown;</a>

        <div  id="comments">
            
        </div>

enter image description here

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 :)

CodePudding user response:

try appending to the comment section instead. maybe youre only grabbing the last one due to overwriting the other values.

commentSection.innerHTML  = `<div>${comment.user_id} says: <br> ${comment.comment}</div>`;

CodePudding user response:

The problem is this part: commentSection.innerHTML

Use an appen DOM manipulation method like appendChild or so.

See also: Is it possible to append to innerHTML without destroying descendants' event listeners?

CodePudding user response:

Use like this. You are assigning a new value in every iteration in innerHtml.

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){
                        let tempStr = ``;
                        comments.forEach(comment => {
                            console.log(comment.comment);
                            tempStr  = `<div>${comment.user_id} says: <br> ${comment.comment}</div>`;
                        });
                        commentSection.innerHTML = tempStr;
                    }
                })
        });

  • Related