0

In my react native code, I'm loading a list of products from firebase firestore, from the products collection, when the app starts. Every product contains a user id. I'm trying to get user information from the users collection for every product.

In other words, I'm trying to build a new array that contains products' information however I want to replace the user id document with user information object.

what is the best way to do that ?

const GetProductsByDate = () => {
    let products_list = []
    const userRef = firestore().collection('users')
    const productsRef = firestore()
        .collection('products')
        .orderBy('date_listed', 'desc')
        .onSnapshot(querySnapshot => {
            products_list = []
            querySnapshot.forEach(async documentSnapshot => {
                products_list.push({
                    ...documentSnapshot.data(),
                    seller : awaituserRef.doc(documentSnapshot.data().seller.id).get().data(),
                    productId: documentSnapshot.id
                })
            })
            setProducts(products_list)
        })
        return() => {
            userRef
            productsRef
        }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

The simplest fix is to set the updated list of products after you load each next user:

const productsRef = firestore()
    .collection('products')
    .orderBy('date_listed', 'desc')
    .onSnapshot(querySnapshot => {
        products_list = []
        querySnapshot.forEach(async documentSnapshot => {
            const user = (await userRef.doc(documentSnapshot.data().seller.id).get()).data();
            products_list.push({
                ...documentSnapshot.data(),
                seller : user,
                productId: documentSnapshot.id
            })
            setProducts(products_list)
        })
    })

If you want to wait for all of them to load before showing any products, see Using async/await with a forEach loop on how to use a for of loop rather than forEach.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your response. but one of the problems that I'm running into is userRef.doc(documentSnapshot.data().seller.id).get()).data() it returns an error but when I replace data() with .then(snapData=>....)it works! – Khaled Ahmed Feb 26 '23 at 14:08