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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With