简体   繁体   中英

Session values on Meteor reset when page reloads

The values I define don't persist when page reloads.

if (Meteor.isClient) {
    Session.setDefault('user_id', null);

    Template.register.events({
        'submit form': function(event){
            var password = getHash(event.target.password.value);
            var name = event.target.name.value;

            console.log(Session.get('user_id')); //always show the default

            var now = new Date();
            password = getHash(password);

            IDS.insert({name: name, online: false, password: password, last_activity: now,last_login: now, created_at: now},function(error,id){
                Session.set('user_id',id);
                //not persisting
            });

            event.target.password.value = '';
            event.target.name.value = '';
        }
    });
}

What am I doing wrong?

As Marius Darila explained in the comments, the meteor Session does not persist accross browser refreshes. It only persists within the client app. When you refresh the page on the browser, it essentially "reboots" the client, resetting its Session to an empty state. (plus whatever variables you set by default at startup, such as your user_id set at null )

By default in Meteor, data can only be persisted across app reboots in the mongodb database. You can find many community packages that give you other means of data persistency, such as the persistent session package for browser localStorage, or CollectionFS for server-side file storage.

Session doesn't persist when you manually refresh a page. All previous answer from pingo and BraveKenny are right on that point. But when Meteor does a Hot Code Reload, it will persist Session data because the refresh has not been asked by user but by the server. This is the only usecase where Session are persisted on a refresh, but it should not happen very often.

Need to add this line:

Tasks = new Mongo.Collection("users");

to the server section:

if (Meteor.isServer) {
 // This code only runs on the server
   Tasks = new Mongo.Collection("users");
}

This will persist the data. Alternatively, you can add it above the if (Meteor.isClient) section of the js file.

https://www.meteor.com/tutorials/blaze/collections

New at this but happen to be learning Meteor as well. Let me know if this works. Thanks !

IMHO, you are not doing wrong, just in an incorrect way! Why don't you use account package and use Meteor.userId() instead? And it is reactive too! Btw session means client local storage, not on server side and its empty every time browser reloads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM