redress redress - 2 months ago 10
Javascript Question

Passing array via ReactiveVar in Meteor

I have a Meteor method that returns all user accounts on my application

returnUsers: function(){
return Meteor.users.find().fetch();
}


I'm using
new ReactiveVar
to pass the return value of the Meteor method into my template helper:

Template.listViewTemplate.created = function (){
var self = this;
self.myAsyncValue = new ReactiveVar("Waiting for response from serv er...");
Meteor.call('returnUsers', function (err, users) {
if (err)
console.log(err);
else
self.myAsyncValue.set(users);
});
}

Template.listViewTemplate.helpers({
userCollection: function(){
return Template.instance().myAsyncValue.get();
}
});


But when I go to render the users into the view, I get a console error that reads


{{#each}} currently only accepts arrays


When I render without the
#each
iterator, using

<ul id='usersList'>
{{userCollection}}
</ul>


the output on my web-page accurately reflects the number of users (2), but reads


[object Object],[object Object]


I'm pretty sure that there is some funkiness going on here because I'm using a global Meteor collection (
Meteor.users.find().fetch()
, as opposed to having defined my own collection), but I'm not sure how to get around it.

I want to display a list of all users so the current user can click another user and share a document with them--not sure how to get around this.

Answer

You don't need to use a reactive variable for this. The function at Template.listViewTemplate.created is not container in an autorun, which means: It won't get recomputed.

The best approach for your scenario is: Use a variable to get the status ( loading, loaded, error) and another variable to save the array itself attach to self. Reactivity is cool but you should only use it when needed.

About:

[object Object],[object Object]

This is happening because you're not extracting any value form the object provided nor looping using {{#each}}.

Your solutions for listing users is dangerous and inefficient. You're sending to the client all the fields from the user collection, including login tokens.

The best approach is to create a subscription that send only the necessaries fields like: _id, info.firstName. You should also have some criteria to the list users and use pagination. Consider also a search feature for such purpose.

Comments