Sort firebase list

1

Currently I use this function to read the data from the firebase database:

function ler() {
    database.ref(referencia_database).orderByChild('nome').once('value').then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
            var chave = childSnapshot.key
            var obj = childSnapshot.val()

            //Verifica se a imagem existe no storage, se sim usa ela, se não usa a padrão
            storage.ref(chave).getDownloadURL().then(function(url) {
                mostrar(chave, obj.nome, url)
            }).catch(function(error) {
                mostrar(chave, obj.nome, './image/default.png')
            });
        })
    })
}

The problem: because of the check mark whether or not the image exists in the (asynchronous) storage, the data is displayed at random.

How do I fix this?

    
asked by anonymous 03.03.2018 / 00:00

1 answer

1

My recommendation is: save the downloadURL of the image in the database when you save the image in Storage. So your object would be, for example:

"exemploObj":{
    "nome":"nomeAqui",
    "url":"https://firebasestorage.googleapis.com/v0/b/..."
    //... Talvez você tenha outros dados aqui ...
}

And then you no longer need to get the downloadURL from storage. You just have to get it from the same bank:

        snapshot.forEach(function(childSnapshot) {
            var chave = childSnapshot.key
            var obj = childSnapshot.val()

            //Verifica se a imagem existe no banco, se sim usa ela, se não usa a padrão
            if(childSnapshot.child('url').exists())
                mostrar(chave, obj.nome, obj.url)
            else
                mostrar(chave, obj.nome, './image/default.png')
        })

To further simplify the code, you can save the path of the default image in the database (instead of leaving this field empty):

"exemploObj":{
    "nome":"nomeAqui",
    "url":"./image/default.png"
    //... Talvez você tenha outros dados aqui ...
}

And then you can remove if :

        snapshot.forEach(function(childSnapshot) {
            var chave = childSnapshot.key
            var obj = childSnapshot.val()
            mostrar(chave, obj.nome, obj.url)
        })
    
03.03.2018 / 01:12