2

I have one node named as group_chat and another one named as users. The node group_chat contains the children which contains message, time and sender_id. Whereas the node users contains the details of users. When I retrieve chats from group_chat node, I also want to display the information of each sender. On using this code

rootChat.on("child_added", function (snapshot) {
    if(snapshot.val().sender_id == logged_in_user_id) {
        // Message by You
        // Print snapshot.val().message
    }
    else{
        const refUser = "/users/"+snapshot.val().sender_id;
        const rootUser = database.ref(refUser);
        rootUser.once("value", function(snap) {
            // Print snap.val().name
            // Display snap.val().picture

            // Print snapshot.val().message
        });
    }
    
});

The problem is, when the code goes in else condition where it's the message of the other user, it retrieves the information of the user by going through the specific node. But while doing it, it automatically goes to next child while going through the user detail of first child which automatically spoils the arrangement of messages showing latest message in the middle, middle one in end and so on. If I have 4 children named as -child1, -child2, -child3 and -child4 in node group_chat, while checking the -child1, it will also check -child2 and sometimes it will print -child 2 before -child1. How can I resolve it? Is there any way where I can wait for the else condition to finish and then go to next child? Or is there any way where I can get user detail in just one line of code somehow like this

// rootUser.child.name 

1 Answer 1

1

How about pre-loading the users, before you start building the HTML?

The outline of that would be something like:

  1. Use on("value" instead of on("child_added, so that you get all messages in one go.
  2. Loop over the messages to determine the unique user IDs.
  3. Load all users with once("value") calls. Note that once() returns a promise, so you can wait to all users to be loaded with Promise.all().
  4. Now loop over all messages again to build the HTML.
  5. At this point if you need user data, you can look it up without needing an asynchronous call.
Sign up to request clarification or add additional context in comments.

1 Comment

Yes that works for me. I was thinking about it but thought maybe it will slow down the process

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.