A very short introduction to ReactiveDict

If you are following the Meteor community news, you probably heard about the proposal of deprecating Session in favor of ReactiveDict. Why?

Because using Sessions you are storing data in a single global dictionary without scope or namespace,  exposing yourself to name collisions and reusability problems.

So, except for the benefits, using ReactiveDict instead of Session, is not a big change, if you take a look to Session source code, you’ll see just one line, saying that Session is a ReactiveDict.

[code language=”javascript”]
Session = new ReactiveDict(‘session’);
[/code]

Ok! How can we use that? Meteor docs tell us how to use Sessions and tell nothing about ReactiveDict…

Indeed, but one of the points of this proposal is changing that, explaining how to use ReactiveDict. Let’s see an short example.

Using Session

[code language=”javascript”]
if (Meteor.isClient) {
setInterval(function() {
Session.set("now", new Date());
}, 1000);

Template.hello.helpers({
now: function() {
var now = Session.get("now");
return moment(now).format("HH:mm:ss");
}
});
}
[/code]

This code runs each 1 second, setting a new value to the key ‘now’ on Session and return it formated by moment.js

Now, let’s do the same thing using ReactiveDict. First include the package.

[code language=”javascript”]
meteor add reactive-dict
[/code]

Although you have to add reactive-dict package, it’s not a third part package, it’s a mdg package just like reactive-var, accounts-password, autopublish, ddp, ejson…

Using ReactiveDict

[code language=”javascript”]
if (Meteor.isClient) {
Data = new ReactiveDict("data");
setInterval(function() {
Data.set("now", new Date());
}, 1000);

Template.hello.helpers({
now: function() {
var now = Data.get("now");
return moment(now).format("HH:mm:ss");
}
});
}
[/code]

So what’s the difference? Just one line, “var data = new ReactiveDict” and we can see the same results written in a better way.

How you can see, using ReactiveDict is not so different of using Session and doing that, you can keep data separated inside a dictionary that makes sense, avoiding confusions and future problems.

 

Leave a Reply