Home > Back-end >  Firestore join user to its collection data in ReactJS
Firestore join user to its collection data in ReactJS

Time:09-18

i want to join user to its datas. In my code below, i can read the data from firestore, but when i try to show the data into table, I only got a post of user's post. Although users have more then one post in posts collection.

enter image description here

In my console.log('this is userData:', userData), it shows this is userData: [{...}] and this is userData: (2) [{...}, {...}]

in my {userData.map((post, index) => {console.log(index, post)})}, the post index is 0 for all post.

may be i missed something in here, how can i fix this?

export default function App () {

    const [userData, setUserData] = useState([]);
    console.log('this is userData:', userData);

    useEffect(() => {
        db.collection('user').doc('idUser').onSnapshot((documentSnaphot) => {
            const posts = [];
            for (let id in documentSnaphot.data().userPosts) {
                db.collection('post').doc(id).onSnapshot((docSnapshot) => {
                    posts.push(docSnapshot.data());
                    setUserData(posts);
                })
            }
        })
    }, []);

    return (
       {userData.map((post, index) => {
           console.log(index, post);
       })}
    )
}

CodePudding user response:

I would recommend to use get instead of a realtime listener and async/await to make the code more clear:

export default function App({ userUid }) {
  const [userData, setUserData] = useState({});
  const [posts, setUserPosts] = useState([]);

  useEffect(() => {
    db.collection("user")
      .doc(userUid)
      .onSnapshot((snap) => {
        setUserData(snap.data());
      });
  }, [userUid]);

  useEffect(() => {
    const posts = [];
    for (let id in userData.userPosts) {
      const postSnap = await db.collection("posts").doc(id).get();
      posts.push(postSnap.data());
    }
    setUserPosts(posts);
  }, [userData]);

  return (
    <div>
      {posts.map((post, index) => {
        console.log(index, post);
      })}
    </div>
  );
}

If you need a realtime listener let me know and I will update the code to have one.

  • Related