Usage of Reactive-Var


#1

Still having some problems understanding the concept of Reactive-Var.

I have a collection AppSettings. When I access it via AppSettings.findOne().settingX everything works reactive: if I change the value in the database, the methods that use settingX are using the updated value.

If I want to have the results of AppSettings.findOne() in a variable now, which is again reactive, how can this be set up?

I tried:

 MyAppSettings = new ReactiveVar(AppSettings.findOne());

However, whenf I call MyAppSettings.get().settingX it does not react to changes in the database. Do I need to put this in Meteor.autorun or something?


#2

Yes. In Meteor, reactive variables are only reactive if they’re used in a reactive environment (a function passed to Tracker.autorun (which was former known as Meteor.autorun) is a reactive environment in Meteor). So, in your case, you would need to do something like this:

MyAppSettings = new ReactiveVar()

Tracker.autorun(function(){
    MyAppSettings.set(AppSettings.findOne());
})

#3

I wonder what would be the use case for a reactive var wrapping a mongo request ?
Also, when you are doing MyAppSettings = new ReactiveVar(AppSettings.findOne()); you are only setting initial value, not subsequent one, is that really what your are trying to do ?


#4

@Peppe_LG thanks for the clarification. @vjau you are right. I thought that moving app settings to a variable and then be able just call AppSetting.settingX, AppSetting.settingY at the relevant places, would be a little nicer than calling findOne() each time.


#5

then you can do

var getSettingX = function(){
return AppSettings && AppSettings.findOne();
};

And if you insert it in a reactive computation (example a helper), it will work.

fooHelper : function(){
console.log(getSettingX());
};

#6

There is a problem.
I tried such code on client side

MyTable = new ReactiveVar();

function some() 
{  
    try
    {
        MyTable.set(  Table.findOne() );
        console.log('Some OK')
    }   
    catch(e)
    { console.log('Some: ' + e.name + ' ' + e.message ) }
}

I got “Some: ReferenceError Table is not defined”

Of course, Table is collection with subscribe. Table is using in code without any problem.


#7

If you’re getting Table not defined, then Table:

  • Is not defined, or
  • Is defined on the server, but not the client (i.e. not in common code), or
  • Is defined within a file scope (using var) in some other file (where it is working).