I have a component that needs to display html based on a boolean variable. I make this variable the same as the one I set in the localStorage. So if I click on foo, I set it to false both as a variable and in the localStorage. If I click on the bar I set it to true. Now, before loading the component I'm going to get this variable, and I make it the same as the one I have locally, so if I clicked on foo, when I reload the component, the variable is false, and therefore the html should show me foo. but I don't understand why he shows me bars!!! It's a bit complicated to explain I hope you understand from the code:
<template>
<div id="app">
<h2 v-if="!isTrue">FOO</h2>
<h2 v-else>BAR</h2>
<button @click="foo()">FOO</button>
<button @click="bar()">BAR</button>
</div>
</template>
<script>
export default {
name: 'App',
data: function () {
return {
isTrue: null,
};
},
created() {
const boh = localStorage.getItem('boh');
this.isTrue = boh;
console.log('boh', boh);
console.log('isTrue', this.isTrue);
},
methods: {
foo() {
this.isTrue = false;
localStorage.setItem('boh', false);
},
bar() {
this.isTrue = true;
localStorage.setItem('boh', true);
},
},
};
</script>
I am attaching an example on stackblitz so maybe you can do tests: https://stackblitz.com/edit/vue-b3ieft?file=src/App.vue
CodePudding user response:
Because a variable you saved in the localStorage is a string. When you do:
const boh = localStorage.getItem('boh');
this.isTrue = boh;
Actually you get:
this.isTrue = 'true';
And this string is always true
.
To avoid this you could check if it is true
string:
const boh = localStorage.getItem('boh');
this.isTrue = boh === 'true';
https://stackblitz.com/edit/vue-mnuhbr?file=src/App.vue
CodePudding user response:
Adding on to @Georgy's answer. To escape an unnecessary check, it is a good practice for booleans to be stringified while setting the localstorage, and parsed when getting the item.
Setting
localStorage.setItem("isDark", JSON.stringify(false));
Getting
const boh = JSON.parse(localStorage.getItem('boh'))