javascriptjquerysession-storage

sessionStorage works but returns "undefined" in console


I just built a jquery plugin to handle some data storages. When I try to read from storage, the result is the read item data.

But when I add

sessionStorage.setItem('test','some data');

or remove

sessionStorage.removeItem('test');

an item, I always get undefined in the console.log

How can I get rid of the undefined?

What I tried was

var result = sessionStorage.setItem('test','some data');

though this would print it to a var but it doesn't.

My code:

(function ($) {
    
    $.storage = {
    
        add: function(name,value){

            if(typeof value === 'object' )
            {   
                /** convert object to json **/
                value = JSON.stringify(value);
            }
            /** add to storage **/
            sessionStorage.setItem(name,value);
        },
        
        read: function(name){
        
            /** read from storage **/
            var item = sessionStorage.getItem(name);
                try {
                    item = $.parseJSON(item);
                }catch(e){}
            return item;
        },
        
        remove: function(name){
            /** delete from storage **/
            sessionStorage.removeItem(name);
        },
        
        clear: function(){
            /** clear storage **/
            sessionStorage.clear();
        }
        
    }
})(jQuery);

Solution

  • setItem and removeItem doesn't return any value. Thus you are getting undefined. Also note removeItem only accept one parameter.

    Reference, Here is function sign for above methods

    setItem(key:string, data:string):void

    This public method stores data via specified key. Please note that if key was already stored, it will overwrite it. Another thing to consider is that if we store a key, and via sessionStorage.key(0) we obtain that key, then we store another key/data and finally we store again the first key, sessionStorage.key(0) will return the second key/data stored, and not the first one.

    removeItem(key:string):void

    This public method simply removes a key and related data from the storage.