Search code examples
mongodbmeteorreactjsflow-router

Cannot subscribe followers inside React Component with Flow-Router/React in Meteor


Issue: I cannot get the followers of a user using Flow-Router + React, subscribing inside React Component

I use Meteor, Flow-Router, React. I'm tring to subscribe followers, but it always returns empty when I run the app. I'm not sure what is wrong.

I follow this approach: Subscribe inside React Component by Arunoda

When I check the query with mongo shell, it works: (i.e. Return the followers (1 user, Bob) of Alice whose _id is "5MJJPc78W3ipXpWzy")

meteor:PRIMARY> db.users.find({followings: "5MJJPc78W3ipXpWzy"}).pretty()
{
  "_id" : "v2Kikp8Wa5FSJi64b",
  "createdAt" : ISODate("2015-12-11T11:08:50.209Z"),
  "services" : {
    "password" : {
      "bcrypt" : "$2a$10$IzfXjbXlYw4BuTMLroSjaOmgqnj8Z9sWXc4uyvHuXurirWRgDcZJ2"
    },
    "resume" : {
      "loginTokens" : [
        {
          "when" : ISODate("2015-12-11T11:08:50.213Z"),
          "hashedToken" : "jN0jeZX6PYFAy6b1eHvwWvbMhiVtbF1cjFySPnTpQTQ="
        }
      ]
    }
  },
  "username" : "bob",
  "followings" : [
    "5MJJPc78W3ipXpWzy"
  ]
}

y codes are here:

lib/router

FlowRouter.route('/users/:userid/followers', {
  name: 'followers',
  action(params) {
    ReactLayout.render(MainLayout, {
      content: <FollowersBox {...params}/>
    });
  }
});

server/publications

Meteor.publish('followers', (userId)=> {
  check(userId, String);
  Meteor.users.find({followings: userId});
});

clients/components/Profile/FollowersBox

FollowersBox = React.createClass({
  mixins: [ReactMeteorData],

  getMeteorData() {
    let data = {};
    let followersSubs = Meteor.subscribe('followers', this.props.userid); // Always empty!

    if(followersSubs.ready()) { // Never be ready
      data.followers = Meteor.users.find({followings: this.props.userid}).fetch();
    }
    return data;
  },

  render(){
    let followersList = "";
    if(this.data.followers){
      followersList = this.data.followers.map((user)=> {
        return <UserItem
              key={user._id}
              userId={user._id}
              username={user.username}
              />
      });
    } 

    return (
      <div>
        <h4>Followers</h4>
        <ul>
          {followersList}
        </ul>
      </div>
    )
  }
});

Full repo https://github.com/yhagio/MeteorReactTwitter


Solution

  • Publish function should return cursor:

    Meteor.publish('followers', (userId) => {
      check(userId, String);
    
      return Meteor.users.find({followings: userId});
    });