2

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.

Jousi
  • 456
  • 4
  • 26
  • Possible duplicate of [localStorage and boolean 'string'](https://stackoverflow.com/questions/30644250/localstorage-and-boolean-string) – Terry Oct 11 '17 at 19:04

1 Answers1

6

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.

Bert
  • 80,741
  • 17
  • 199
  • 164
  • Ok I understand the issue with localstorage, but not sure if the solution you proposed applies in this situation, because the computed method is dependent on the outcome of the `if()` statement which I am commenting out. – Jousi Oct 11 '17 at 19:34
  • @Jousi I updated the example pen so that the reactive example uses a computed that works off the data value instead of the local storage value. – Bert Oct 11 '17 at 19:41