1

I'm using reactJS to create a simple social media app. This is the schema of my database:

--- posts (collection)
         |
         --- uid (documents)
              |
              --- userPosts (collection)
                    |
                    --- postId (documents)
                    |     |
                    |     --- title: "Post Title"
                    |     |
                    |     --- date: September 03, 2018 at 6:16:58 PM UTC+3
                    |
                    --- postId (documents)
                          |
                          --- title: "Post Title"

I would like posts to be refreshed in real time with onSnapshot method. How to get ALL of my posts? I changed the structure of my database like you see and I don't know how to get my posts that are nested. This is how I did it before when all of my posts were in "posts" collection.

const [posts,setPosts]= useState([]);

useEffect(() => {
        db.collection('posts').onSnapshot(snapshot =>{
            setPosts(
                snapshot.docs.map(doc=>({
                  id: doc.id,
                  post : doc.data()
                })));
        })
     }, [])

1 Answer 1

1

You can access the nested posts by providing the path to it, like this:

const [posts,setPosts]= useState([]);

useEffect(() => {
        db.collection('posts').onSnapshot(snapshot =>{
           snapshot.docs.map(doc=>({
             doc.collection('userPosts').onSnapshot(snapshot =>{
               setPosts(
                 snapshot.docs.map(doc=>({
                   id: doc.id,
                   post : doc.data()
               })));
             });
           }));
        });
     }, []);
Sign up to request clarification or add additional context in comments.

2 Comments

But the problem is that it is not a 'uid' but it is a uid of the user. There are many different uids there because every user can post.
@dodododo97 If you want ALL Posts of a single user, you can put the uid of the user in place of 'uid'. And If you want ALL Posts of ALL Users, then check the code I've just updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.