I have a computed
method:
computed: {
currentPosition () {
if(this.get_local_storage_state()){
return this.lastLocation
}
if (this.currentRestaurant) {
return this.currentRestaurant.address.location
} else if (this.searchPosition.lat && this.searchPosition.lon) {
return this.searchPosition;
} else {
return null;
}
}
}
Which is getting called in my <template>
:
<GMap class="c-splitview__map" :markers="getMarkers" :position="currentPosition" :zoom="currentZoom" v-if="currentPosition" />
<div class="m-storefinder__placeholder" v-else>
<h1 class="o-headline">{{$tc("storefinder.emptyDeeplink")}}</h1>
</div>
And for some reason, when it gets called the first time, it works how it should, however when I try calling it again (re-rendering the Vue component) it doesnt get called.
BUT!
When I comment out the first if()
statement, like so:
computed: {
currentPosition () {
// if(this.get_local_storage_state()){
// return this.lastLocation
// }
if (this.currentRestaurant) {
return this.currentRestaurant.address.location
} else if (this.searchPosition.lat && this.searchPosition.lon) {
return this.searchPosition;
} else {
return null;
}
}
}
It works how it should again.
The this.get_local_storage_state()
function looks like this and is located in methods:{}
:
get_local_storage_state(){
let state = localStorage.getItem('McDonaldsStoreWasOpen');
return state === "true" ? true : false;
}
I am basically trying to use local storage as a state management system.
localStorage
is not reactive and cannot be observed. That, combined with the fact that computed values are cached, means that when you are pulling the value out of local storage in the computed, the result will be cached and the computed will always return the same value after that. That's also why the computed resumes working when you remove the value from localStorage
.
I would recommend instead, that you initialize a data value from localStorage
, use that value in your computed, and then save the value back to localStorage
at a later specified time.
Here is a codepen demonstrating the difference.