Home > Mobile >  javascript foreach object and get the result in a state
javascript foreach object and get the result in a state

Time:11-16

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

CodePudding user response:

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

CodePudding user response:

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

  • Related