Firebase val() returns an empty object but when I use the console after the page is loaded, the object is there

I have the following part of the code where I try to copy an object from Firebase but it logs as empty but when everything finishes loading I can access to the object. My function gives "Cannot read property 'title' of undefined" error and doesn't work unless I call it from the console. Works but still gives the same error.

I am really stuck and don't know what to look for so all the help would be appreciated!

let dataRef = database.ref('books');
let firstbook = document.getElementById('firstbook');
let arr = []

dataRef.on('value', data => {
    arr = (data.val())    
})
console.log(arr) 


function getList(){
    for(i=0; i < 5; i++) {
        let a = document.createElement('p')
        a.textContent = Object.values(arr)[i].title
        firstbook.appendChild(a)
        console.log(a)
    }
}

1 answer

  • answered 2021-05-03 18:11 shapkar

    When and where do you call the getList function? Probably you should call it within the .on listener inside the handler, after storing the data in the "arr".