Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor couldn't hold a session's value among pages

Tags:

meteor

I'm facing a problem that Meteor couldn't hold a session's value if a Web page is moved to a other Web page. I'm new for Meteor, maybe I'm misusing. How do I handle session's value among pages? I want to keep session's value even if the page move to the other page or browser is reloaded.

I'm planing to build a Web application using Javascript framework such as Meteor, Mojito, and Express (Node.js) and testing them before developing.

I'm using Meteor version 0.5.2 (6635ae1007) and Chrome version 23.0.1271.95.

Here is a test code and steps for test:

(1) Click the 'TEST' button:

This changes 'Result is' labels to 'Result is OK'.

(2) Click the 'Back to Top page' link or reload the browser:

I want to hold the label 'Result is OK' but it goes back to 'Result is'. It means session value is undefined.

test.js

if (Meteor.isClient) {
  Template.test.result = function() {
    var result = Session.get('TEST');
    console.log('Result: %s', result);
    return result;
  }

  Template.test.events({
    'click' : function() {
        Session.set('TEST', 'OK');
    }
  });
}

test.html

<head>
  <title>sample-session</title>
</head>

<body>
  <h1>Session Test</h1>
  <a href="./">Back to Top page<a/><br/>
  {{> test}}
</body>

<template name="test">
  <input type="button" value="TEST"></input><br/>
  Result is {{result}}.
</template>
like image 327
Ryuta Aoki Avatar asked Dec 06 '12 16:12

Ryuta Aoki


1 Answers

UPDATE Meteor now has a Session.setDefault method that does exactly what you're expecting.

Original Answer Below

The session object in meteor is fundamentally different from the session concept in other frameworks (Rails/ASP.NET MVC/PHP) -- its primary function in Meteor is to serve as a reactive variable for client side code.

It is not designed to do what you're expecting above -- as soon as your link fires, the client context is wiped, and any client-side session values are gone. Meteor apps aren't designed for navigation in the traditional sense, so that's why this seems so confusing. It's completely understandable :)

Instead of approaching navigation in the traditional sense, I suggest you take a look at meteor-router, which helps ease the transition between traditional and a more meteoresque approach.

If you do need to persist data the way you're describing above, you'll want to look into the amplify smart package for persisting data on the client locally.

TIP: as you learn about Meteor in the docs, pay very close attention to the designation of client / server / anywhere in the upper right of each segment.

like image 118
TimDog Avatar answered Oct 28 '22 11:10

TimDog