Reputation: 5427
I have a chat functionality in my project. When someone is sending a message I update the database using push.
And I define a method called renderChatUI.
I define a listener like this:
firebase.database().ref(`USERS/${Database.getNestedData('UID')}/UserClass/${grade}/${subject}/Topics/${key}/Chats`).on('child_added', (snapshot) => {
console.log('Hello');
this.renderChatUI(UID, grade, subject, key);
})
So that, every time any message is added to this path, my chat UI re-renders.
The child_added block of code executes perfectly, but the renderChatUI() method doesn't trigger the first time (when I add first message). When adding second message, chat UI re-renders with first Message, when adding third chat UI re-renders with second and so on...!
I can't figure out whats going wrong. I appreciate your help.
Upvotes: 0
Views: 258
Reputation: 80914
To allow the child-added
to trigger after adding to the database, then you can use a completion callback, for example:
firebase.database().ref('users/' + userId).set({
username: name,
email: email,
profile_picture : imageUrl
}, function(error) {
if (error) {
// The write failed...
} else {
// Data saved successfully!
firebase.database().ref(`USERS/${Database.getNestedData('UID')}/UserClass/${grade}/${subject}/Topics/${key}/Chats`).on('child_added', (snapshot) => {
console.log('Hello');
this.renderChatUI(UID, grade, subject, key);
})
}
});
}
From the docs:
The optional completion callback that is called when the write has been committed to the database. If the call was unsuccessful, the callback is passed an error object indicating why the failure occurred.
Upvotes: 2