VueJS is massively useful tool. And, I love churning out SFCs like there’s no tomorrow.
Vue helps us provide a super user experience. Combine it with Vuetify, Buefy and the like, and you have an application that is loved by all.
Except, when the user hits F5 in the browser.
Refreshing the browser will reset state. The typical state stored with Vuex is dissolved and may take the auth./login info with it if you have designed auth. in such a way. This is not a good experience for anyone.
One of the ways in which this problem can be solved is by pushing the state in Vuex to local storage. By doing that not only are the auth. details saved across browser sessions, but we can cache static data to make our application ‘feel’ faster.
Vue does not provide a standard way to manage local storage. Although it is not difficult to push the state to local storage by yourself (see this), you can speed up the process by leveraging Vue plugins.
There are two popular plugins that do this job well -
While I started with vuex-persistedstate, which appears to be more popular of the two, I switched to vuex-persist in the projects that I did over the last six months. I refrain from directly comparing them since they are both great plugins, but I liked the way vuex-persist is documented.
vuex-persist provides the following functionality -
- save state to local storage
- support for multiple types of storage incl. local storage
- use filters to selectively store state
- store partial states
- .. and the most appreciated of them all - save parts to local storage and parts to session storage
How to use vuex-persist?
You only have to do two things -
- Install vuex-persist
yarn add vuex-persist
- Read docs at https://github.com/championswimmer/vuex-persist
How I use vuex-persist?
This is opinionated usage of vuex-persist. So, don’t start shooting (yet).
As is typical, I have Vuex modules for entities. Variables are centralized and stored in the Vuex module unless they are hyper-local to a component.
Next, identify three types of modules -
- Variables that need to go to cookie (e.g. authentication token)
- Variables that need to go in local storage (e.g. Todo detail )
- Rest of variables that can stay in Vuex state (e.g.
Todolist query results)
Local storage is not secure and data in the storage can be accessed by all and sundry - hence the need to send sensitive data incl. auth. information and tokens to cookies.
Not all variables need to be stored - identify the modules and variables that need to be.
Subsequently, make changes to Vuex store. In
index.js (the main vuex store), initialize vuex-persist by introducing the following code.
That’s all there is to it. Enjoy your life knowing that data is safe in local storage no matter how many times the user refreshes his browser.