skip to Main Content

I am iterating over an object from firestore subcollection and I can only console log the result, but I am not able to add the result in a state to use it in a flat list. I tried many ways to get the result in an array but no success.

  const [order, setOrder] = useState()
useEffect(()=>{
    const fetchOrder = async()=>{
        const orderRef = doc(db, "Order", route.params.orderId)
        const orderCollectionRef =  collection(orderRef, "products")
        const q = await query(orderCollectionRef)
        const getOrder =await getDocs(q)
        getOrder.forEach(doc=>{
            console.log(doc.data())

            //i can console log the result but i want to get it in a state to use it in flatlist
        })
        
        
    } 
    fetchOrder()
},[])

this is the console log of getOrder enter image description here

and this is the console log of doc.data()
enter image description here

3

Answers


  1. Chosen as BEST ANSWER
       const fetchOrder = async()=>{
            const orderRef = doc(db, "Order", route.params.orderId)
            const orderCollectionRef =  collection(orderRef, "products")
            const q = await query(orderCollectionRef)
            const getOrder =await getDocs(q)
            let orders = []
            getOrder.forEach(doc=>{
                //this is the right way to push the orders to an array
                orders.push({
                    ...doc.data(),
                    id: doc.id
                })
            })
            setOrder(orders)
        }
    

  2. you can see example in in this main page site, i saw something similar that work

    Login or Signup to reply.
  3. I hope this helps, creating a temp array then push the orders using forEach, then using setState.

    const getOrder =await getDocs(q)
    const temp = []
    getOrder.forEach(doc=>{
                temp.push(doc.data()))
    setOrder(temp)
    

    I am not sure whether if you want to have it in the right order as the original, for safe, you may also consider to use ‘for await of’ instead of forEach

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search