Get information if the feed is liked by the user in a single query (Firestore)

前端 未结 2 1666
天涯浪人
天涯浪人 2021-01-19 18:33

I want to show feeds for my users.
Every post has a \"like\" button (like in twitter, Instagram...)
I want to show a different icon if the post is already liked o

2条回答
  •  无人共我
    2021-01-19 19:24

    You could create an array within each post containing the userID's of the users who liked the post.

    // data model
    
    posts/{postID}
      -- content (string)
      -- likes: [
           user123,
           user567,
           user895,
      ]
    
    

    Then query the posts like so.

    db.collection('posts')
      .orderBy('createdAt', 'desc')
      .limit(50)
    

    Then inside the snapshot.

    db.collection('posts')
      .orderBy('createdAt', 'desc')
      .limit(50).get()
      .then(snapshot => {
        if (snapshot.empty) {
          console.log('No matching documents.');
          return;
        }  
    
        snapshot.forEach(doc => {
          console.log(doc.id, '=>', doc.data());
    
          var liked = false;
          var likes = doc.data().likes;
    
          if (likes.includes(user_uid){
             liked = true
          }
    
          return createPost(doc.data(), liked);
    
    
        });
      })
      .catch(err => {
        console.log('Error getting documents', err);
      });
    

    Then below create a function called createPost() taking parameters data and likedStatus.

    Add {likedStatus ? "You liked this" : "Like post"} into your createPost function.

    createPost = (data, likedStatus) => {
    
      return (
        
    {likedStatus ? "You liked this" : "Like post"}
    ) }

提交回复
热议问题