0
votes

I am trying to display the email address of the logged in user with Meteor.

I am using the command Meteor.user().emails[0].address -- and this works sometimes only. Other times it is undefined. This is because sometimes the page renders before the User's collections is available.

However, I am using React and not blaze. Every solution online suggests using Meteor.subscribe() in the onCreated part of the template. But I cannot figure out React's equivalent and I cannot figure out how to wait for the User collection before rendering.

1

1 Answers

0
votes

Updated to use Meteor.autorun which accepts a callback function that runs whenever Meteor's reactive sources update.

Meteor.subscribe accepts an onReady optional callback. I would attach to the componentWillMount lifecycle event on your React component, setup your meteor subscription, and cause a state change once onReady has fired. Here is some rough example code;

var Foo = React.createClass({
  componentWillMount: function() {
    var _this = this;

    // Setup meteor subscription
    Meteor.autorun(function () {
      _this.setState({
        user: Meteor.user(),
      });
    })
  },
  render: function() {
    // Render nothing until we have a user
    if (!this.state || !this.state.user) {
      return null;
    }

    // Render the address when we have the user

    return (
      <div>{this.state.user.emails[0].address}</div>
    );
  }
});

Relevant docs: http://docs.meteor.com/api/pubsub.html#Meteor-subscribe