ZuzEL
ZuzEL

Reputation: 13675

Why does storing a ReactiveVar in Session convert it to a plain Object?

If I store a ReactiveVar in Session and then read it, I see that my ReactiveVar gets converted to an Object.

var v = new ReactiveVar(4)
Session.set("v", v)
Session.get("v") //Object {curValue: 4, dep: Object}

I can't get or set it any more because it is a plain object.
Does anybody know the point of it?

PS: ReactiveVar inside another ReactiveVar works great

Upvotes: 1

Views: 117

Answers (1)

Kyll
Kyll

Reputation: 7151

Session is a global named ReactiveDict.
All reactive dictionaries have a very funny feature : They stringify your data for storage.
They do so in order to store it across hot code pushes for example.

Consider the following code :

var dict = new ReactiveDict()
dict.set('foo', { func : function() {} })
console.log(dict.get('foo'))

The console will output :

Object { }

And that is because EJSON stringification (defined by Meteor) is based off JSON stringification, which removes object methods and prototypes to strictly keep data.

If you want to store a reactive value coming from a ReactiveVar into Session, you will have to run a Tracker computation to do it :

Tracer.autorun(
  () => Session.set('foo', foo.get()) 
)

If you want to reactively store an object with methods or a defined prototype, use ReactiveVar.

Upvotes: 1

Related Questions