newdeveloper
newdeveloper

Reputation: 1451

Firestore: How to iterate through some documents and get the sub collections?

Currently I am loading all companies from a property based on propertyId, as shown below from firestore:

  useEffect(() => {
    const loadCompanies = () => {
      try {
          setLoading(true);
          return firebase
            .firestore()
            .collection(`/properties/${user.propertyId}/companies`)
            .orderBy('companyName', 'asc')
            .onSnapshot((querySnapshot) => {
              const allCompanies = [];
              querySnapshot.forEach((doc) => {
                allCompanies.push({
                  id: doc.id,
                  ...doc.data(),
                });
              });
              setCompanies(allCompanies);
              setLoading(false);
            });
      } catch (error) {
        console.log(error);
        setError(error.message);
      }
    };

    if (user) {
      return loadCompanies();
    }
  }, [user]);

I have an array of propertyIds now and need to repeat the same process for each propertyId

How should I iterate through each propertyId and store all companies in one variable and then update the state in the end?

I tried to use Promise.all but I think I am not doing it right.

Upvotes: 0

Views: 328

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

Something along the following lines should do the trick:

//...
const firestore = firebase.firestore();
const propertyIds = ['p1', 'p2'];
const promises = [];

const allCompanies = [];

propertyIds.forEach(propID => {
    promises.push(firestore.collection(`/properties/${propId}/companies`).orderBy('companyName', 'asc').get());
});

Promise.all(promises)
    .then(querySnapshotArray => {
        querySnapshotArray.forEach(querySnapshot => {
            querySnapshot.forEach((doc) => {
                allCompanies.push({
                    id: doc.id,
                    ...doc.data(),
                });
            });
        });
        setCompanies(allCompanies);
        //...
    });

Instead of using onSnapshot() which attaches a listener for QuerySnapshot events, we use the get() method, which executes the query and returns a promise that resolves with a QuerySnapshot -> we can then use Promise.all().

Upvotes: 1

Related Questions