Search code examples
javascripthtmlrequirejssession-storage

sessionStorage not immediately available


In the example below (and in the jsfiddle, dependant on requirejs) the console outputs theUsername and http://nothing&username=null the first time through and then if you run it again it outputs as you'd expect (i.e., http://nothing&username=theUsername)

define('environment', {
    myData: 'http://nothing&username=' + sessionStorage.getItem('username')
});

require(['environment'], function (environment) {
    sessionStorage['username'] = 'theUsername';

    console.log(sessionStorage.getItem('username'));
    console.log(environment.myData);
});

Previous edits

I couldn't figure out how to set this up in a jsfiddle with all the dependencies, but here is a simple version demonstrating the problem in azure. The page doesn't actually do anything and hits a dead connection string so you'll have to look at it through the browser dev tools or firebug.

http://tomdev.azurewebsites.net/www/index.html

Ok, hopefully the last update... I was able to get this displaying the problem in jsfiddle, very simple, small example. Watch the console in Chrome. Run it once and you'll see the problem, hit run again and you'll see it's working now.

http://jsfiddle.net/JhK5L/1/


Solution

  • You're initializing myData in your define() call with whatever value is in sessionStorage['username']. Therefore, the first time you call define() the value is null, and is not set until you initialize sessionStorage['username'] in your require() function.

    Instead of initializing myData to a string, make it a getter function that retrieves the current value at invocation:

    define('environment', {
        myData: function() { return 'http://nothing&username=' + sessionStorage.getItem('username'); }
    });
    
    require(['environment'], function(environment) {
        sessionStorage['username'] = 'theUsername';
    
        $("ul").append('<li>' + sessionStorage.getItem('username') +'</li>');
        $("ul").append('<li>' + environment.myData() +'</li>');
    });