React-native & redux combining actions fetching from firestore

I am new to React-Native and building an app with it and firebase/firestore as a BaaS/DB

The app has a feed, where all posts should be displayed, and each of this post should have a different screen component in which more data from it can be rendered, including info about the post creator.

One of the main problem is that the posts and creators are in different collections in firestore. So I will need to get the post data, then take the field creatorId(which is a field in each post doc, that creatorId = the doc id from users collection) and fetch on users collection where the firestore doc = creatorId from that post.

I've already managed to get this working without Redux, but, there are a lot of reads being made. First, on feed all posts are read, then on each post, each time a users goes to the screen component, 2 reads are being made, another one for post, and one for user data.

So I started using Redux to only fetch posts & their users once, in feed, then keep all that data in store. But due to my level of knowledge and experience, I couldn't find a way for this to properly search users based on their creator field of posts, and combine them.

ACTIONS:

export function fetchAllPosts() {
return((dispatch) => {
    firebase.firestore()
                .collection('allPosts')
                .get()
                .then((snapshot) => {
                    let posts = snapshot.docs.map(doc => {
                        const data = doc.data();
                        const id = doc.id;
                        const creator = doc.data().creatorId; //Need to fetch by this
                        return { id, creator, ...data }
                    })
                    
                  dispatch({type: POSTS_STATE_CHANGE, posts })
                })
    
})
}

Needed apart from this: another action to fetch post's creators data (firebase.firestore().collection('users').where(id, '==', 'posts.creator').doc()....

And then be able to combine them(so that I make sure each post has its own creator, not any errors)

REDUCER:

const initialPostsState = {

posts: [],


};


export const feed = (state = initialPostsState, action) => {
 switch(action.type){
     case POSTS_STATE_CHANGE:
         return {
             ...state,
             posts: action.posts
        };
        
     default: 
        return state;
 }

};

Would truly appreciate some help and guidance!



Read more here: https://stackoverflow.com/questions/68462244/react-native-redux-combining-actions-fetching-from-firestore

Content Attribution

This content was originally published by flaneurx at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: