Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor js : make Session object partially persistent

Tags:

session

meteor

In my meteor app I'm using Session to store temporary info about user activity. I'd like to persist some parts of this info to the browser with amplify.js, but not all of it.

I'd like a way to have 'temporary' Session keys and 'persistent' Session keys. Eg I could call

Session.set('persistent', 'this is persisted to browser memory');
Session.set('temporary', 'this will be erased on page reload, etc');

and then after a page reload

Session.get('persistent'); // returns 'this is persisted to browser memory'
Session.get('temporary'); // returns undefined

I found a related post on SO but this saves this approach persists the entire Session object, which I don't want to do. Also, I don't want to use MongoDB for this, I'd like the storage to be purely client side...

Many thanks in advance!

like image 649
Petrov Avatar asked Oct 27 '13 11:10

Petrov


1 Answers

Use localStorage. It's a little tricky if you want it to be reactive, but I guess you could use Session to get that done alongside localStorage

When starting up get the item from your browser's localStorage jar

Meteor.startup(function() {
    Session.set("yourItem", localStorage.getItem("yourItem"));
});

When setting it:

localStorage.setItem("yourItem", "yourValue");
Session.set("yourItem", localStorage.getItem("yourItem"));

One thing that's not possible unless you use MongoDB or something is if you set this on one tab, it wont change on the others until you refresh the page. But I guess Session is like this anyway.

like image 147
Tarang Avatar answered Sep 30 '22 18:09

Tarang