0

I try to get data from cloud firestore inside my actions on google app. I want to search for an object and then want to extract the link to the image in to an array. If more objects were found the links should be pushed all in the array.

This is what I have:

let array = []; //Everything should be in here

var collectionRef = db.collection('shoes');
var query = collectionRef.where('sport', '==', 'tennis');

query.get().then(function(results) {
    if(results.empty) {
      console.log("No documents found!");   
    } else {
      // go through all results
      results.forEach(function (doc) {
        array.push(document.data().name);
      });
    }
  }).catch(function(error) {
      console.log("Error getting documents:", error);
  });



var prodpic = array[0]; // Array is not filled because in output always "undefined"

I do want to work with the img-links in prodpic in my later program. I hope my problem is clear and anyone can help me to find my mistake.

1 Answer 1

1

Data is loaded from Cloud Firestore asynchronously. This means that by the time you assign var prodpic = array[0] it hasn't been loaded yet.

This is easiest to see by replacing most of the code with a few log statements:

console.log("Before starting query");
query.get().then(function(results) {
  console.log("In query results");
})
console.log("After starting query");

When you run this code the output is:

Before starting query

After starting query

In query results

This probably isn't what you expected, but explains perfectly why your var prodpic = array[0] doesn't work: the data hasn't been loaded yet, so array[0] is empty.

To deal with asynchronous loading, you have to make sure that your code that needs the data is inside the then() callback. So:

query.get().then(function(results) {
  if(results.empty) {
    console.log("No documents found!");   
  } else {
    // go through all results
    results.forEach(function (doc) {
      array.push(document.data().name);
    });
    var prodpic = array[0]; 
  }
}).catch(function(error) {
  console.log("Error getting documents:", error);
});

For more on this, also read Doug's blog post here: https://medium.com/google-developers/why-are-firebase-apis-asynchronous-callbacks-promises-tasks-e037a6654a93

One additional optimization: if you only care about the first matching document, it's more efficient to use a limit query:

var query = collectionRef.where('sport', '==', 'tennis').limit(1);
Sign up to request clarification or add additional context in comments.

1 Comment

Thx this is what I searched for! I hat read about the asynchronous thing before but now I have seen it on my on Code it became clear!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.