rishat
rishat

Reputation: 8376

Subscribe to Meteor.users collection updates

I use react-komposer and React in my app and at one point I change user's profile property of Meteor.users collection item that reflects current user. The problem here is that it doesn't reactively loopback in a call of render. Whatever I do to Meteor.users collection, even though I refer to Meteor.user() within render function, doesn't re-render the component. If I do

render() {
  console.log('rendered');

  /// ...
}

then I can only see "rendered" on the console twice: once the component has been initially rendered and the second time other subscriptions are ready.

I'd like to subscribe to Meteor.users collection but I don't know if there's a way to do.

I could definitely use Tracker to react to every Tracker loop but it feels too 1.2 to me. But is it the only way to do?

Also, I definitely have read other Q&As about Meteor.users like this one or this one but the idea of wrapping users collection into pub/sub directly feels unnatural, and hardly is a good way to listen to every update in the collection.

Upvotes: 0

Views: 676

Answers (1)

rdk1992
rdk1992

Reputation: 406

You have to make a publication on the server code regarding the meteor.users collection.

    Meteor.publish('allUsers', function allUsers() {
      return Meteor.users.find({}, {
        fields: {
          services: 0,
        },
     });
   });

Then you can subscribe on your container to that publication and query Meteor.users collection and send that result to the component.

const composer = (props, onData) => {
const userHandle = Meteor.subscribe('allUsers');
if (userHandle.ready()) {
    const users = Meteor.users.find({}).fetch();
    onData(null, {
        users,
    });
}
};
export default composeWithTracker(composer)(YourComponent);

After this any change done to the collection inside YourComponent will be reflected client side.

Upvotes: 2

Related Questions