Display user data with post data in one flatlist. Merge two Firebase firestore collections into one end result

Viewed 34

I have a post feed combining of two firebase firestore collections.

userPosts = [] // collectionGroup() query of all users images

users = {} // the users data after for looping posts results

I'm currently getting both the posts from the post collection and the users data from the users collection after for looping the post uids.

This is working fine and shows the user object combined with the post object in the console.log() but It will not show in the flatlist when combining this end result to a state hook!

Basically, it seams to be working fine but I can't display it. I need the end result to be the post with the users data retrieved after for looping.

Again, console.log shows correct merge of data, attaching to state hook and displaying in flatlist is not working.

My code:

    useEffect(() => { // showGlobal feed
        if (showGlobalFeed) {
            firebase.firestore()
                .collectionGroup("userPosts")
                .orderBy("creation", "asc")
                .get()
                .then((snapshot) => {

                    let posts = snapshot.docs.map(doc => {
                        const data = doc.data();
                        const id = doc.id;
                        const uid = data.uid;
                        return { id, uid, ...data }
                    })

                    for(let i = 0; i< posts.length; i++){
                        firebase.firestore()
                        .collection("users")
                        .doc(posts[i].uid)
                        .get()
                        .then((snapshot) => {
                            if (snapshot.exists) {
                                let user = snapshot.data();
                                user.uid = snapshot.id;


// the below cosloe.log works fine.

                                console.log('\nFOR LOOP COMBINED ==========> \n',[posts[i], user])

// the hook fails to display combined data correctly
                                setGlobalPosts([posts[i], user])
                            }
                            else {
                                console.log('does not exist')
                            }
                        })
                    }
                   // console.log({...posts})
                })
            }

    }, [showGlobalFeed])


Flatlist = data={globalPosts}


0 Answers
Related