Sort firebase list

Asked

Viewed 501 times

1

Currently I use this function to read data from 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 checkpoint whether the image exists in the (asynchronous) Path, the data is displayed randomly.

How to solve this?

1 answer

1


My recommendation is: save the image downloadURL in the bank 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 take the downloadURL of the Storage. Just have to take 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 default image path 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 take the if:

        snapshot.forEach(function(childSnapshot) {
            var chave = childSnapshot.key
            var obj = childSnapshot.val()
            mostrar(chave, obj.nome, obj.url)
        })
  • I do not save anything from the image in the database (Realtime database), take the image by the name of the file that is the same as the object key, it is better to change to how you showed?

  • Yes, that’s my suggestion.

  • Okay, but I want only one image to be registered for each object, and I’ll organize Storage like this: /chave/nome_receita.png, can tell me how to delete the images from one directory and set another, regardless of the name, since the user can change the image and the file name will probably be different

Browser other questions tagged

You are not signed in. Login or sign up in order to post.