2

I am trying to export a firestore function that performs a query and returns an array containing the objects in that query. I am trying to get data from a subcollection of a document, and get an array of document objects returned to render to the client.

I've tried the below but it's not working (e.g. the object returns blank). I think this has to do with improper handling of promises, but couldn't figure it out on my own. Thanks for your help.

export const getEvents = (id) => {
  let events = [];
  firestore.collection('users')
    .doc(id)
    .collection('events')
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => events.push(doc));
    });
    return events;
 };

1 Answer 1

3

You are correct in identifying this problem is related to the handling of promises. You are returning the events array before it has a chance to be populated, because the promise hasn't resolved yet.

If your environment allows it, I would recommend that you use async/await, because it makes the code much easier to read and understand, like this:

export const getEvents = async (id) => {
    let events = [];
    const snapshot = await firestore.collection('users')
        .doc(id)
        .collection('events')
        .get()
    snapshot.forEach((doc) => events.push(doc));
    return events;
};

But if you can't use async/await you can do it with promises. But you need to only resolve the promise after the data is fetched:

const getEvents = (id) => {
    return new Promise((resolve, reject) => {
        let events = [];
        const snapshot = firestore.collection('users')
            .doc(id)
            .collection('events')
            .get()
            .then((snapshot) => {
                snapshot.forEach((doc) => events.push(doc));
                resolve(events); // return the events only after they are fetched
            })
            .catch(error => {
                reject(error);
            });
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you - I'll try this out and follow up if I run into any more problems.

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.