Waiting on Meteor.user ()

If new users subscribe, I take them to the initial route, so they can enter a name that is in /gs . I store the name inside the name property of the current user profile object. Now, if a user who has already entered a name and visits the /gs route, I want to redirect them to the root directory. In an iron router, I do this:

 Router.route('/gs', { name: 'gs', onBeforeAction: function() { if ( Meteor.user().profile.name ) { this.redirect('/'); } else { this.render(); } } }); 

Although this works, it prints 2 errors to the console. One of them is "Unable to read property" profile of "undefined" and the absence of this.next() . Any way to fix these problems.

+5
source share
2 answers

Route functions and most interceptors run in reactive computing. This means that they will restart automatically if the source of the reactive data changes. For example, if you call Meteor.user () inside your route function, your route function will be repeated every time the value of Meteor.user () changes. ( Iron.Router Guide: Reactivity )

The interception functions and all the functions that are launched when they are sent to the route are performed in reactive calculation: they will be restarted if any sources of reactive data cancel the calculation. In the above example, if Meteor.user () changes the entire set of route functions, it will be started again. ( Iron.Router Guide: Using Hooks )

At the first start of the function Meteor.user() is undefined . Then its value is changed to an object. Since this is a reactive variable, the function starts again, with no errors this time.

You should check if Meteor.user() exists before using its properties. Here is a very (perhaps too much) comprehensive way to do this:

 if (Meteor.user() !== undefined) { // the user is ready if (Meteor.user()) { // the user is logged in if (Meteor.user() && Meteor.user().profile.name) { // the name is already set this.redirect('/'); } else { this.render(); } else { // the user is not logged in } else { // waiting for the user to be ready } 
+5
source

Pandark has the right answer, wants to share his working code!

 Router.route('/account',{ fastRender: true, data:function(){ if( Meteor.user() && Meteor.user().profile.guest ){ Router.go('/login'); } else { Router.go('/account'); } }, template:'screen', yieldTemplates: { 'account': {to: 'content'}, } }); 
0
source

Source: https://habr.com/ru/post/1208991/


All Articles