I’m creating a new project to get acquainted with using React and Meteor together. I’m following along with the docs but have a problem with reactive data, particularly Meteor.user().
Cannot read property ‘username’ of undefined
&
Cannot read property ‘_currentElement’ of null
However, if I: let { currentUser } = this.data;
inside of the render function, and then log { currentUser },
it runs twice, the first time returning undefined, and the second time returning the correct object.
For what its worth, I am trying to render the username of the current user inside the header of my page, and I am using kadira:react-layout to render the header component as part of a layout.
basically react is not waiting user to return data before it renders it self, so intially your currentUser is null until the subscription is connected and data is fetched.
To avoid this you can put this in the render method
let renderContent;
if(this.data.currentUser){
renderContent = <span>Hello {this.data.currentUser.username}!</span>;
}else{
//you can do a loading template here or just leave blank
}
return renderContent;
Your issue is that of a race condition as @sikanx mentioned but I think @shock has pointed out a better solution if fast render does server side rendering before passing the first page to you which would eliminate any race condition.
Fast render runs the waitOn function (or one of the Fast Render API calls) on the server and gets the subscription data relavant to the page you are loading. Then it sends that data along with the initial HTML
I’ll rephrase a bit. It’s doable, but not recommended. Works better in Iron Router than Flow Router BTW, since Flow Router is not reactive (and routers shouldn’t be)… plus Flow Router will eventually be dropping subscription support anyway.