SkintMedia
SkintMedia

Reputation: 33

Data returns correctly but won't display the returned data properly?

So I'm currently struggling to view the returned data in a p and textarea element.

Here's the function I'm using, you can see that I am receiving each key from the comments node and getting the comment title and message and that works as it should...

function loadComments() {
    var comments =
        firebase.database().ref('/comments').once('value', function(snapshot) {
            snapshot.forEach(function(data) {
                var childData = data.val();
                var childKey = data.key;
                console.log(childData.title + " " + childData.message);
                Elements.commentTitle.text(childData.title);
                Elements.commentMessage.text(childData.message);

                var clonedNode = $('.listItems:last').clone();
                $(clonedNode).insertAfter('.listItems:last');
                $(clonedNode).css({
                    display: "block"
                });
            });
        });
}

However when i try to view the data in the 2 elements, It will only show the title and message from the first node and that will duplicate depending on how many comments have been sent.

So for example, If say there were 5 comments, all with different data, so title and message were different. This is what you will see...

 Title
  Message

 Title
  Message

 Title
  Message

 Title
  Message

 Title
  Message

Also just in case it helps, here is the html code I'm using....

<div class="container listItems text-left w-75 justify-content-center" style="display: none">
        <p class="titleBody"><strong></strong></p>
        <ul><p class="commentBody"></p></ul>
</div>

Upvotes: 2

Views: 51

Answers (1)

mikkpokk
mikkpokk

Reputation: 78

The problem is that you clone existing element. You should replace data right after element has been cloned.

Code below fixes the problem you complained about.

function loadComments() {
    var comments =
        firebase.database().ref('/comments').once('value', function(snapshot) {
            snapshot.forEach(function(data) {
                var childData = data.val();
                var childKey = data.key;

                var clonedNode = $('.listItems:first-child').clone();
                clonedNode.find('.titleBody:first-child > strong:first-child').text(childData.title);
                clonedNode.find('.commentBody:first-child').text(childData.message);
                clonedNode.insertAfter('.listItems:last-child');
                clonedNode.css({
                    display: "block"
                });
            });
        });
}

Upvotes: 2

Related Questions