0

i am trying to do realtime message with firebase using javascript but i have problem with onChildAdded because everytime i click button to change user onChildAdded returns previous repeated values. Is there a way to get onChildAdded to be called again but not return previous values?

function selectAdmin(reciveName) {
    onChildAdded(newMsg, (data) => {
        
        if ((data.val().senderName === reciveName) && (data.val().reciveName === currentUser)) {
            console.log(data.val());
            messagesContainer.append([
                `<li class="other"><span><img src="${data.val().senderAvatar}" alt=""></span>`,
                data.val().message,
                `</li>`
            ].join(''));
        } else if (data.val().senderName === currentUser && data.val().reciveName === reciveName) {
            var currentName = data.val().senderName;
            messagesContainer.append([
                `<li class="self"><span><img src="${data.val().senderAvatar}" alt=""></span>`,
                data.val().message,
                `</li>`
            ].join(''));
        }
    });
}




$('ul').on('click', '.chat_with_user', function() {
    var id = $(this).attr('id');
    reciveName = id;
    messagesContainer.html('');
    selectAdmin(reciveName);
    messagesContainer.finish().animate({
        scrollTop: messagesContainer.prop("scrollHeight")
    }, 250);
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • When you call `onChildAdded`, you add a persistent listener. If you want to stop listening, you'll need to [detach that listener](https://firebase.google.com/docs/database/web/read-and-write#detach_listeners). -- Do consider though if you actually need to call `onChildAdded` each time `selectAdmin` is called. Right now it seems that you're always calling `onChildAdded` on the same reference (`newMsg`), so as far as I can tell you end up listening to the same data each time. – Frank van Puffelen Jun 01 '23 at 13:28

0 Answers0