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?
Asked
Active
Viewed 6,171 times
1
-
Possible duplicate of [Is there any way to 'watch' for localstorage in Vuejs?](https://stackoverflow.com/questions/42974170/is-there-any-way-to-watch-for-localstorage-in-vuejs) – Steven Spungin May 26 '19 at 20:00
-
@StevenSpungin no, it another case – Eugene Chefranov May 26 '19 at 20:02
-
"(because localstorage is not react in vue)" localStorage is not react . Not only in Vue The only posibility I see is to subscribe state, or actions in vuex. Then checks localStorage every time you try to do something. – Adam Orłowski May 26 '19 at 20:06
-
Although that's not what you're asking, I'd suggest you to, if possible, reconsider your app architecture, because even tho polling would work, it's imperative and not the best in terms of performance. Since you haven't exposed your code, it's hard to suggest something concrete, however maybe look into vuex if you haven't already! – Feel The Noise May 26 '19 at 20:15
2 Answers
1
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)

Bergur
- 3,962
- 12
- 20
0
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)
}

Steven Spungin
- 27,002
- 5
- 88
- 78