Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieving values from all keys returns undefined with Firebase Realtime Database in JavaScript

In a small application I am making, I am trying to retrieve a specific note title and text from a parameter from a function I created. The parameter is a key.

function viewNote(note) {
    alert(note)
    var fetchedNote = database.ref('Users/' + localStorage.getItem('username') + "/Notes/" + note)
    fetchedNote.on('value', (snapshot2) => {
        var data = snapshot2.val()
        for (var key in data) {
            var value = data[key]
            var ti = value.title
            var te = value.text
            console.log(ti + ", " + te)
        }
    })
}

When I try to get all keys from parent key Notes, I get all child nodes without undefined errors. They work fine, but when I try to get a child node information title and text from Notes key, I get undefined. What can I do in such cases? Thank you for your time.

What I tried and What I want:
I tried by using the code above but still undefined error, I also used let before but still it doesn’t work.
I want the title and text key values instead of undefined. Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since you’re getting a single node with a direct path to that node, the snapshot you get back contains only that node. So you don’t need to loop over its children.

var fetchedNote = database.ref('Users/' + localStorage.getItem('username') + "/Notes/" + note)
fetchedNote.on('value', (snapshot2) => {
    var value = snapshot2.val()
    var ti = value.title
    var te = value.text
    console.log(ti + ", " + te)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading