Eugene Chefranov
Eugene Chefranov

Reputation: 171

Vue. How to watch localstorage for changes?

Another script (no vue.js) write some data in localstorage, for example array "links". But my vue app see it only after page reload (because localstorage is not react in vue). How can I watch localstorage for changes and show without reload page?

Upvotes: 2

Views: 7243

Answers (2)

Steven Spungin
Steven Spungin

Reputation: 29071

If you want to see changes in local storage that are made outside your influence, you can poll it.

data() {
    return {
      lastChange: null,
      timer: null
    }
  },
  created() {
    let curVal = localStorage.getItem('foo');
    this.lastChange = new Date()
    this.timer = setInterval(() => {
      const newVal = localStorage.getItem('foo');
      if (newVal !== curVal) {
        curVal = newVal;
        // fireEvent, update state, etc
        // or update data in your component
        this.lastChange = new Date()
      }
    }, 1000);
  },
  beforeDestroy() {
    cleaInterval(this.timer)
  }

Upvotes: 0

Bergur
Bergur

Reputation: 4057

Local storage isn't really designed for dynamic data that's constantly updating, but lets assume you can't control that.

VueJS only watches data in its components, so you can't use VueJS.

One solution, that isn't pretty is using setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) that would run every x seconds and get the value from localStorage.

It's not pretty or efficient, bu something like

let name = 'Bergur'
setInterval(function() {
name = localStorage.getItem('name')
}, 5000)

Upvotes: 1

Related Questions