0

I am working on a project with vuejs3. I need to save some data somewhere globally and call another page. I was using local storage for this, but this doesn't feel right and it gets harder to manage as the project grows.

at user login

lookie.set("userType", "student")

at another component

lookie.get("userType")

For example, there are two user types as student and teacher in the project, I keep their user type in the local storage at the user login, and I do not display some components if the user type in the local storage is student. I used the state structure, but it didn't work for me because it reverts to its default value when the page is refreshed. What kind of structure do you think I should set up?

Serkan Gün
  • 332
  • 1
  • 2
  • 12
  • Use State Management library like Vuex or Pinia and override the getter and setter with local storage data manipulation methods – Alpesh Patil Jun 27 '22 at 18:34
  • Since you're on Vue3, use Pinia: https://pinia.vuejs.org/ – kissu Jun 27 '22 at 18:44
  • FWIW, both Vuex and Pinia have persistence plugins – Estus Flask Jun 27 '22 at 18:47
  • yes i used it but when i refresh the page the state reverts to its old default value @kissu – Serkan Gün Jun 27 '22 at 18:53
  • 1
    You of course need some way to persist it, so localStorage is a good way. Conclusion, use `localStorage` + `Pinia` to have both a global state + persistency. More details available here: https://stackoverflow.com/a/66872372/8816585 – kissu Jun 27 '22 at 18:56
  • @SerkanGün You can use state management to get the data from the store with in a application and local storage to get it whenever user refresh the page as on refresh state will get reset and initialize again. – Debug Diva Jun 27 '22 at 19:10
  • As kissu pointed out, you need both advantages: persistence (which is provided by localstorage) and flexibility in structuring data (provided by pinia). The solution is to save the state of Pinia in localStorage (as a string) and to load it on page load, if it's found. Pinia comes with a [persistence plugin](https://github.com/prazdevs/pinia-plugin-persistedstate) which handles it for you with minimal setup. You can configure which state props are saved or which are not, etc... – tao Jun 27 '22 at 19:43

0 Answers0