Cannot Set Boolean Values in Localstorage

Cannot set boolean values in LocalStorage?

Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).

So in your case the boolean is converted to a string.

As for why "true" != true, as written in the description of Equal (==) in MDC*:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

Note that the string is converted to a Number instead of a Boolean. Since "true" converted to a number is NaN, it will not be equal to anything, so false is returned.

(*: For the actual standard, see ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)


Edit: The setItem interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail.

How to have localStorage value of true?

I was wondering if its possible for localStorage to have a Boolean value instead of a string?

No, web storage only stores strings. To store more rich data, people typically use JSON and stringify when storing and parse when retrieving.

Storing:

var test = true;
localStorage.setItem("test", JSON.stringify(test));

Retrieving:

test = JSON.parse(localStorage.getItem("test"));
console.log(typeof test); // "boolean"

You don't need JSON for just a boolean, though; you could just use "" for false and any other string for true, since "" is a "falsey" value (a value that coerces to false when treated as a boolean).

Store booleans in javascript's localStorage?

The W3C Storage interface specifies that values (and keys) are strings:

Each Storage object provides access to a list of key/value pairs,
which are sometimes called items. Keys are strings. Any string
(including the empty string) is a valid key. Values are similarly
strings

Boolean toggle and save to localStorage not toggling addClass

Many answers talking about using toggleClass(), which is fine - but that's not your real problem.

You're using $(this) to try and find an element, but this isn't referencing what you think it's referencing. In this instance, its the scope of the wishList() function - not the element that was clicked.

Add event into your onclick event;

<button onclick="wishList(event)" ...>...</button>

Then for your wishList() function use event.target to reference the clicked element;

function wishList(event) {
var element = event.target;
localStorage.setItem('wishlists', !addToWishlist);
$(element).find('.fa').toggleClass('add-to-wishlist', !addToWishlist);
}

To add the class when you load the page, you just need to grab the data from local storage, and then add the class if required.

However, as you'll need to reference the element directly rather than based off the event above - it may be better to always reference the element directly anyway.

For example, just have this inside your $(document).ready() function;

var lsWishList = localStorage.getItem('wishlists');
if(lsWishList == true) {
$(".wishlist").find('.fa').addClass('add-to-wishlist');
}

A note about what's TRUE

Be careful when using this comparison. A string value will return as TRUE (with ==) - and as Local Storage can only be reliably used to store strings you might need rethink how you're storing that data.

Cannot set boolean values in LocalStorage?

Firefox's implementation of Storage can only store strings, but on 2009 September, W3C modified the draft to accept any data. The implementation (still) isn't caught up yet (see Edit below).

So in your case the boolean is converted to a string.

As for why "true" != true, as written in the description of Equal (==) in MDC*:

If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

Note that the string is converted to a Number instead of a Boolean. Since "true" converted to a number is NaN, it will not be equal to anything, so false is returned.

(*: For the actual standard, see ECMA-262 §11.9.3 “The Abstract Equality Comparison Algorithm”)


Edit: The setItem interface was reverted to accept strings only on the 2011 Sept 1st draft to match the behavior of existing implementations, as none of the vendors are interested in supporting storing non-strings. See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 for detail.

handle addEventListener in if condition based on localStorage boolean value

I think the problem is you are adding an event listener but you never removed it thus it's always listening for that event.

Try adding/removing event listener conditionally like below

function changeListener(event) {
if(event.matches) {
themeDiv.classList.add("dark");
themeDiv.classList.remove("default");
} else {
themeDiv.classList.add("default");
themeDiv.classList.remove("dark");
}
}

let osTheme = window.matchMedia('(prefers-color-scheme: dark)');
if(localStorage.getItem('systemOption') === 'true') {
osTheme.addEventListener('change', changeListener);
} else {
osTheme.removeEventListener('change', changeListener);
}

OR

Listen for event always and apply theme conditionally by checking localStorage

const osTheme = window.matchMedia('(prefers-color-scheme: dark)');
osTheme.addEventListener('change', event => {
if(localStorage.getItem('systemOption') === 'true') {
if(event.matches) {
themeDiv.classList.add("dark");
themeDiv.classList.remove("default");
} else {
themeDiv.classList.add("default");
themeDiv.classList.remove("dark");
}
}
});


Related Topics



Leave a reply



Submit