0

When I console.log the data I get from firestore inside the then() function as shown below, it displays the data without the problem. However, if I append that data in the peopleData variable and console.log the peopleData variable, I get an empty string.

let db = getFirestore();
let peopleCollection = collection(db, 'People');

getDocs(peopleCollection)
.then((people) =>{
    people.docs.forEach(person =>{
        let personData = person.data(person);
        console.log(`${personData.Name} is an ${personData.Occupation} aged ${personData.Age}`);
    })})
.catch(err =>{
    console.log(err)
})

Here I get an empty string logged

let peopleData = ``;
getDocs(peopleCollection)
.then((people) =>{
    people.docs.forEach(person =>{
        let personData = person.data(person);
        peopleData += `${personData.Name} is an ${personData.Occupation} aged ${personData.Age}`;
    })})
.catch(err =>{
    console.log(err)
})

console.log(peopleData);
Vincent
  • 1
  • 1
  • 1
    Well yes, that's how asynchronism works. `getDocs` is asynchronous, it's a Promise that gets resolved later in time, inside the `.then`, long after `console.log(peopleData)`. What's the problem exactly? – Jeremy Thille Jan 07 '22 at 07:51
  • Since data is loaded from Firestore (and most modern cloud APIs) asynchronously, the code in your `then` block gets executed (much) later then the code immediately *after* that block. Any code that needs the data from Firestore needs to be inside the `then` callback, be called from there, or be otherwise synchronized. See https://stackoverflow.com/questions/60691965/unable-to-add-google-markers-inside-a-loop/60694259#60694259 – Frank van Puffelen Jan 07 '22 at 16:17

0 Answers0