0

I'm trying to figure out what the setItem method from sessionStorage returns. As far as I could get, the following code returns undefined:

var set = sessionStorage.setItem('foo', 'bar');
console.log(set);

I need to know if the item was successfully set or if it failed. How can I accomplish this without knowing the return?

darksoulsong
  • 13,988
  • 14
  • 47
  • 90
  • Possible duplicate of [Cannot set boolean values in LocalStorage?](http://stackoverflow.com/questions/3263161/cannot-set-boolean-values-in-localstorage) – T.Todua Aug 24 '16 at 15:59

4 Answers4

7

Take a look at the sessionStorage specification.

This line:

setter creator void setItem(DOMString key, DOMString value);

Tells us setItem doesn't return anything. (void is the return value, there)


You can check if the item was set like this:

if (sessionStorage.getItem('myValue') == null){
    // myValue was not set
}else{
    // myValue was set
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

Here is a guide on sessionStorage from the Mozilla Developer Network. It appears that sessionStorage.setItem(name, value) does not return anything.

However, if you manually wanted to check, you could try something like this:

sessionStorage.setItem('make', 'Ford');

/* Returns null if it cannot find the item in sessionStorage. */
if(sessionStorage.getItem('make')) {
    /* Session storage set successfully. */
} else {
    /* Session storage did not set successfully. */
}
War10ck
  • 12,387
  • 7
  • 41
  • 54
0

Use try catch expression, since the method throws an exception if the session is full, as stated in the specification :

try { sessionStorage.setItem('foo', 'bar'); }
catch(oops) {
     // maybe no more space, try to free
     localStorage.removeItem('foo');
     sessionStorage.setItem('foo', 'bar');
}
Community
  • 1
  • 1
Jisay
  • 21
  • 1
0

I want to add in case someone will have the same issue as me. (im a beginner in js btw).

I was following this thread and trying the below but the if was firing when entering the page (on first load).

sessionStorage.setItem('test',false);    
if (sessionStorage.getItem('test') != "false") {
   ..........
}

What did it for me was changing != to ==. So in my case it looks like this:

//other function that sets session and reloads
sessionStorage.setItem('reload', 'false');
location.reload();

//then the if after reload
if ( sessionStorage.getItem('reload') == 'false' ) {
//whatever you want here
//setting it true again so it doesn't fire when I manually reload.
sessionStorage.setItem('reload', 'true'); 
}

I find it a bit counterintuitive because you'd think to set the session to true and then fire the if if session != false... but hey it works, doesn't fire on first page load and then fires when i execute the page reload.

agenciq
  • 11
  • 1