Firebase once() triggered more than once

I'm trying to retrieve data from firebase with js in a flask app. Although it kinda works, it's executed a lot more times than once. This is my code. I'm just trying to get the messages id's, save them on an array and then adding them when the chatbox is opened. I just want it to execute once. what can I do?

This is my code:

//Getting the messages id of the logged in user from firebase and pushing them into the array
firebase.database().ref().child("user-messages").child("{{usuario}}").once('value', function(snapshot) {
        snapshot.forEach(function(child) {
           console.log("Child:  " + child.key + "//////" + child.val());
           var msg = {};
           msg.key = child.key;
           msg.val = child.val();


//Looping the array and looking for the messages on firebase
for(i = 0; i < mensajes.length; i++){
        firebase.database().ref().child("Mensajes").child(mensajes[i].key).once('value', function(childsnapshot) {
                var id;
                if(mensajes[i].val == "1"){
                    id = usuario[0].nombre.split(" ")[0];
                    user = buscarUsuario(childsnapshot.val().to);
                } else if(mensajes[i].val == "2"){
                    user = buscarUsuario(childsnapshot.val().from);
                    id = user.nombre.split(" ")[0];

                if (user.user == usuarios[index].user){
                        chat.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);
                    } else{
                        div.chatbox("option", "boxManager").addMsg(id, childsnapshot.val().message);

So, the first iteration it works, executes 5 times, only got 5 messages:

But then, I get this (goes on and on and on, never stops, page crashes):

enter image description here

What am I doing wrong?

Thanks in advance :)

1 answer

  • answered 2018-10-19 22:23 Doug Stevenson

    You're calling once() inside a for loop. So, of course, you can expect it to execute for each time it's called in the loop, the length of mensajes.