Question

I just build a jquery plugin to handle some data storages. when i try to read from storage, the result is the read item data. fine for now....

when i add

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

or remove

sessionStorage.removeItem('test');

a item, i allways get a undefined in the console.log

but it do what i it should do.

how can i get rid of the undefined, any ideas ???

what i tried was

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

thought this would print it to a var but it won'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

I tried to add storage in console... when i used it in my script it returned nothing! SORRY

Was it helpful?

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.

OTHER TIPS

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

does not return anything.

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

assigns value to 'test'therefore the right hand side does not have any value. What you want is

sessionStorage.setItem('test','some data');
var result = sessionStorage.getItem('test'); //<- here the right hand side is 'some data'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top