Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getDoc().then() inside of a loop Firebase

I am trying to loop through an array and for each element in an array i want to use getDoc() and then add the data of the document to a new array. Basically to do this:

useEffect(() => {
    let items = [];
    for(const cart_item of cartItems){
        getDoc(doc(getFirestore(), 'tickets', cart_item.ticket_id)).then((ticket_item) => {
            items.push({...ticket_item.data()});
        });
    }
    console.log(items);
}, [cartItems])

However, the items array is still empty after a loop where i log it. I think that the issue is that the loop is not waiting for the getDoc() to return something and goes on. How to make it wait for the getDoc() to finish? I have been reading about async, await but i still don't understand how to handle it.

like image 307
AidasV Avatar asked Sep 16 '25 22:09

AidasV


1 Answers

Try refactoring your code with an async function as shown below:

useEffect(() => {
  const getItems = async () => {
    // fetching all documents by mapping an array of promises and using Promise.all()
    const itemsDocs = await Promise.all(cartItems.map(c => getDoc(doc(getFirestore(), 'tickets', c.ticket_id)))
    // mapping array of document data
    const items = itemsDocs.map(i => i.data())
    console.log(items);
  }
  getItems();
}, [cartItems])
like image 109
Dharmaraj Avatar answered Sep 19 '25 14:09

Dharmaraj