Get Firebase Collection into simple array

Viewed 374

I am trying to react all items from a collection in Firebase into an array so I can use later in React.

I have this currently:

  const retrievegear = firebase.firestore().collection('gear').get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      const check = doc.data().Name;
        console.log(check);
    });
  });

Which is fine - it shows me all the Names of the items in the gear collection. But I want it within an array and only want some of the fields in the collection.

I am then using this array to populate checkboxes - so I need const declared somewhere so that my return can access it.

1 Answers

The Firestore get() method is asynchronous and returns a Promise, so it’s only in the callback function passed to then() that you get its result.

Consequently you need to do as follows:

const myArray = [];
firebase.firestore().collection('gear').get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      const check = doc.data().Name;
        console.log(check);
        myArray.push(check);
    });
    // Here do whatever you want with the myArray array which contains the data from the collection

  });

If you want to transform this code in a function that you can call from other places in your code, do as follows (we use async/await for readability):

async function getGearData() {
    const myArray = [];
    const querySnapshot = await firebase.firestore().collection('gear').get();
    querySnapshot.forEach(doc => {
        const check = doc.data().Name;
        console.log(check);
        myArray.push(check);
    });
    return myArray;
}

Note that this function is asynchronous, so you need to call it as follows:

getGearData()
.then(gearData => {
  // Here and only here you get the value 
  console.log(gearData);
  // ....
})

Note that you can also use the map() method on the array returned by querySnapshot.docs.

Related