Persistent Sessions in Meteor
Asked Answered
C

2

8

So, one of the more confusing aspects I've been observing with Meteor is that Sessions get cleared every refresh. Since it isn't a persistent store, where would I put things like userid, or where people are in my application's state machine?

What are the patterns for those scenarios?

Congest answered 29/7, 2012 at 0:55 Comment(0)
O
8

Actually what you could do is create a "subclass" of Session that stores the value in Amplify's local storage when set() is called. You would automatically inherit all the reactive properties of Session. Here is the code, it worked for me:

SessionAmplify = _.extend({}, Session, {
  keys: _.object(_.map(amplify.store(), function(value, key) {
    return [key, JSON.stringify(value)]
  })),
  set: function (key, value) {
    Session.set.apply(this, arguments);
    amplify.store(key, value);
  },
});

Just replace all your Session.set/get calls with SessionAmplify.set/get calls. When set() is called, the parent Session method is called, as well as amplify.store(). When the "subclass" is first created, it loads everything that is in amplify's store inside its keys, so that they can be retrieved right away with get().

You can test a working variation of the Leaderboard example here: https://github.com/sebastienbarre/meteor-leaderboard

Ong answered 2/2, 2013 at 5:56 Comment(1)
Nice. I found this for something else, but I'm totally going to use this idea. Thanks, Sebastien!Mordred
E
3

Well, for a start I would be using meteors built in Auth to store userID. They are using local storage by default there I think, but AFAIK there's no easy way to hook into that.

However, I would have thought if you want stuff to survive across refreshes you should either store it in mongo or use the URL to indicate where they are in the 'state machine'. You can use the bootstrap router (for example) to use pushState to change the URL.

Encircle answered 29/7, 2012 at 7:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.