1

I use LocalStorage to persist some content of my Vue3 app. Today, I just write to LocalStorage any changes in the content I want to preserve and read from that contact in specific cases (an interval, or some other trigger).

The last part is not optimal because I need to have complex logic about how to make the LocalStorage → app update (LocalStorage can be updated by "something else", and this update should reflected in the app)

The solution would be to bind the content of LocalStorage with a reactive variable, which would natively bring two advantages:

  • any change in the variable or LocalStorage is reflected in the other one
  • changes are naturally persistent

Question 1: Is this something that is possible (Vue3 and a modern browser)?

Question 2: I recently heard about FileSystem which seems to be a possible alternative to LocalStorage, but I do not know it enough to assess whether it could be more suited to solve my problem?

Note: there is a similar question (How to make data from localStorage reactive in Vue js) but it does not cover Vue3 and the possible use of FileSystem. The answer is basically "it is not possible natively. I will mark it as a duplicate if this is still the case.

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • This is usually done with global store, because LS is global either. And there are ready to use solutions for Vuex, etc – Estus Flask Nov 25 '21 at 08:38
  • @EstusFlask: I do have a global store (for other reasons), the problem is how to do the reactive binding between the two. – WoJ Nov 25 '21 at 08:53
  • With Vuex plugin. It uses `storage` event internally. – Estus Flask Nov 25 '21 at 09:14
  • @EstusFlask: I just have a basic knowledge of Vuex (I checked if it was useful for my project by reading the docs) - so sorry if the question is obvious bur: does Vuex manage internally the LocalStorage events to mutate the states? I cannot find anything about that in its docs. – WoJ Nov 25 '21 at 10:39
  • It's not. But it has everything to make it possible. E.g. https://github.com/robinvdvleuten/vuex-persistedstate There's a lot of similar Vuex questions that cover this – Estus Flask Nov 25 '21 at 12:24
  • @EstusFlask Thanks for the feedback. It is not really a binding between the two entities, rather a way to persist data between page reloads (and yes, there are several libs that do it I saw in various places). I guess that a true biding is not directly doable then. – WoJ Nov 25 '21 at 13:13

1 Answers1

0

If I understand your question right, if you are updating localStorage at one place, it should also update on other pages.

I never tried this, but I can think of two approaches.

WoJ
  • 27,165
  • 48
  • 180
  • 345