Meteor.user().profile returns 'profile' undefined - javascript

I have a helper called 'isActive' and a template named 'create'.. see below
Template.create.isActive = function () {
return Meteor.user().profile.isActive;
};
When I try to run this code it returns the following in console: "Exception in template helper: TypeError: Cannot read property 'profile' of undefined".
Basically I want to pull the 'isActive' info from the current user profile and return it to the template. Any idea why this does not work?
Update
//startup on server side:
Meteor.publish("userData", function() {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'profile.isActive': 1}});
} else {
this.ready();
}
});
//startup on client side
Meteor.subscribe('userData');
//router
this.route('list', {
path: 'list',
waitOn : function () {
return Meteor.subscribe('userData');
},
data : function () {
return Meteor.users.findOne({_id: this.params._id});
},
action : function () {
if (this.ready()) {
this.render();
}
}
});

Meteor.user() is undefined. You are either not logged in with any user or your template is rendered before the users collection is synced to the client. If you use a router like iron router you can wait for the collection being available or for the user being logged on.
Without using a router the easiest would be to check if the user is defined:
Template.create.isActive = function () {
return Meteor.user() && Meteor.user().profile.isActive;
}
Since Meteor.user() is reactive the template will be rerendered when the user changes, i.e. when it is available.
This is a common error btw, see also:
Meteor.user() Error: Uncaught TypeError: Cannot read property 'name' of null
How can I prevent Meteor.user()'s timing hole?

Related

Meteor.user() is undefined in client-side controller

In the client-side of a METEORJS application, i have a controller that display some users.
I have a problem with Meteor.user() function, the error is : Meteor.user(...) is undefined.
Here is my code :
this.AdminUsersController = RouteController.extend({
template: "Admin",
yieldTemplates: {
'AdminUsers': { to: 'AdminSubcontent'}
},
onBeforeAction: function() {
var permissions = Meteor.user().profile.permissions;
if (permissions && permissions.indexOf('Users') != -1)
this.next();
else this.redirect('/admin/dashboard');
},
action: function() {
if(this.isReady()) { this.render(); } else { this.render("Admin"); this.render("loading", { to: "AdminSubcontent" });}
/*ACTION_FUNCTION*/
},
isReady: function() {
var subs = [
Meteor.subscribe("users")
];
var ready = true;
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
var data = {
params: this.params || {},
users: Users.find({labo_id: Meteor.user().profile.labo_id}, {sort: {createdAt:-1}})
};
return data;
},
onAfterAction: function() {
}});
It's in the data function.
I try to retrieve all users that are connected to the logged in user and got the same labo_id field...
I don't know why it give me that, because in the onBeforeAction function, i can access to Meteor.user(), and specially his profile...
Someone know what can i do to make it run ?
Thanks for your future answers :)
This is a timing issue. Meteor.user() does not necessarily return data, if it hasn't been loaded yet. Meteor.userId() however will return the _id of the user record (if they are logged in). If you can change your query to rely on that _id, then it can work.
Depending on which router you are using, you can add a resolve: entry to ensure that the route waits for the user record to be loaded before activating it, and then your query will work.

Ember Route: Cannot read property ‘id’ of undefined

I'm getting this error, where I am trying to retrieve a user that DO NOT exist on purpose ofcouse:
Error while processing route: user Cannot read property 'id' of
undefined TypeError: Cannot read property 'id' of undefined
Instead of this console error, can I give the user an error message saying, 'the user does not exist' or something like that through the route or a controller to the view?
Heres my route
App.Router.map(function () {
this.resource('user', { path: '/user/:user_id' });
});
And here i retrieve the user
App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('user', params.user_id);
},
});
Hope you understand and can help me proceed. Thanks in regards!
So I'm not sure why missing fixtures data is giving you that particular error, but you can catch errors in routes using the error event. You can read about it here. You'll have to do something like this:
App.UserRoute = Ember.Route.extend({
model: function(params) {
return this.store.find('user', params.user_id);
},
actions: {
error: function(error, transition) {
// Display some sort of message
alert("Sorry, we couldn't find that user.");
// Redirect to a different part of the application
this.transitionTo('index');
}
}
});

this._id undefined in Meteor

I am trying to set my selectedDocId upon routing to a page, but Meteor is throwing undefined . I am using an onBeforeAction in an attempt to store the id that is concatenated at the end of my url via /:id, but I can't get them aligned.
Router.route('speaker', {
path:'/speakers/:_id',
template: 'speaker',
data: function(){
return Speakers.findOne(this.params._id);
},
onBeforeAction: function(){
console.log('speaker route has run');
Session.set('selectedDocId', this._id);
//returns undefined
console.log(this._id);
this.next();
}
});
Template.speaker.helpers({
editingDoc: function(){
return Speakers.findOne({_id: Session.get('selectedDocId')});
}
});
Instead of this._id, use this.params._id just like you did in the data hook.

Object #<Object> has no method 'User'

everyone. I have a problem with my code and Meteor 0.9.4
Here is my code:
Server/publications.js
Meteor.publish('getUsers', function () {
var loggedInUser = Meteor.User();
if (Roles.userIsInRole(loggedInUser, ['admin'])) {
return Meteor.users.find({}, {fields: {
_id: 1,
emails: 1,
roles: 1
}});
}
this.stop();
return;
});
Lib/router.js
Router.map(function() {
this.route('dashboardUsers', {
layoutTemplate: 'dashboardLayout',
path: "/dashboard/users",
waitOn: function() {
return Meteor.subscribe('getUsers');
}
});
});
When I run meteor app, I have the following error:
=> App running at: http://localhost:3000/
I20141019-18:21:50.827(4)? Exception from sub 8CRiG3Jmdv4mohPhd TypeError: Object #<Object> has no method 'User'
I20141019-18:21:50.949(4)? at null._handler (app/server/publications.js:3:31)
I20141019-18:21:50.950(4)? at maybeAuditArgumentChecks (packages/ddp/livedata_server.js:1594)
I20141019-18:21:50.950(4)? at _.extend._runHandler (packages/ddp/livedata_server.js:943)
I20141019-18:21:50.950(4)? at _.extend._startSubscription (packages/ddp/livedata_server.js:769)
I20141019-18:21:50.951(4)? at _.extend.protocol_handlers.sub (packages/ddp/livedata_server.js:582)
I20141019-18:21:50.951(4)? at packages/ddp/livedata_server.js:546
If you have a look at the docs for Meteor.user, you'll see it works everywhere except publish functions. You need to do:
var loggedInUser = Meteor.users.findOne(this.userId);
The error your getting is because of the upper-case 'u' in Meteor.User it should be Meteor.user.
However, as David Weldon pointed out you'll need to use Meteor.users.findOne(this.userId) inside of publish functions.
For anyone else running into the error Object #<Object> has no method 'user' when trying to access Meteor.user() be sure you have the accounts-base package.

iron-router waitOn Meteor.user()

I would use Meteor.user() in data iron-router, but this is undefined at start...
I'm trying with:
waitOn: function() {
return curretUserHandle;
},
data: function() {
// access to Meteor.user().username, give me undefined
[...]
var curretUserHandle = {
ready: function () {
return 'undefined' !== typeof Meteor.user();
}
};
but data function of route is always call before curretUserHandle.ready() return true
I know that i can add if(Meteor.user()) in data, but this option don't like.
Why data don't wait that Meteor.user() is ready?
Adding https://atmospherejs.com/meteorhacks/fast-render 'magically' solves this.
However, please read the note on necessary security measures:
https://meteorhacks.com/fast-render/security-measures/
Only as workaround can be used:
if(this.ready())
in data function

Categories

Resources