sessionStorage setItem returns true or false
Asked Answered
T

4

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?

Tenebrae answered 31/1, 2014 at 13:57 Comment(1)
Possible duplicate of Cannot set boolean values in LocalStorage?Coveney
F
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
}
Flagitious answered 31/1, 2014 at 14:0 Comment(1)
I think this will do for now... assuming that if something goes wrong, NULL is returned.Tenebrae
J
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. */
}
Juror answered 31/1, 2014 at 14:3 Comment(0)
B
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');
}
Brenza answered 31/1, 2014 at 14:5 Comment(0)
A
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.

Auction answered 22/11, 2022 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.