I'm working on a project that requires me to update a UI based on how many values exist in the database. For instance, when 2 child values are created, the UI updates to contain two boxes.
Currently, my code determines how many child objects exist;
database.ref("parent").on('value', displayValue);
function displayValue(c){
total = c.numChildren()
}
From here, I create how ever many elements, based on this number. My problem however, is how to get the initial child name, in this case, "child1" to update elements such as the title text.
Is there a way to pull these values based off an index, like in a javascript array array[index]?
CodePudding user response:
The Firebase Realtime Database API does not have a way to access child nodes by their index. The only way to pull a child by index, is by loading all children into an array in your code, and then access them by index there.
If you want to iterate over all the child nodes in your snapshot, you can do:
database.ref("parent").on('value', (snapshot) => {
snapshot.forEach((child) => {
console.log(child.key); // "child1", "child2"
console.log(child.child("data").val()); // "123", "123"
});
}
If you want to update a specific child, you specify the keys for the entire path. For example:
database.ref("parent").child("child1").child("data").set("456")
Or a bit shorter:
database.ref("parent/child1/data").set("456")