If you have worked with Vue or Nuxt application, I am sure you have had a hard time managing the sessions, storing cookies, and working with localStorage.
Luckily we have a vuex-persistedstate package to help us with all these.
You just need to install the package and configure it for your project. That's it. All your browser refreshes won't affect the application state.
Install
// npm
npm install vuex-persistedstate
// OR
// yarn
yarn add vuex-persistedstate
Usage
vuex-persistedstate 3.x (for Vuex 3 and Vue 2)
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()],
});
vuex-persistedstate 4.x (for Vuex 4 and Vue 3)
import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";
const store = createStore({
// ...
plugins: [createPersistedState()],
});
Example with Nuxt.js
Create a file persistedState.client.js
inside the plugins directory.
Note: Naming your plugin 'xxx.client.js' will make it execute only on the client-side. Learn more
// ~/plugins/persistedState.client.js
import createPersistedState from 'vuex-persistedstate'
export default ({ store }) => {
createPersistedState()(store)
}
Then, update your plugins inside the nuxt.config.js
file.
// Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
plugins: [{ src: '~/plugins/persistedState.client.js' }],
That's it, your Nuxt.js application is now state persistent and will be able to handle manual browser refreshes.
That's it for this post.
If you want to see how it works in a Vue.js application, please leave a comment below, I will include that too.
Live Demo using vuex-persistedstate
: https://magic-nuxtjs.vercel.app/login
I have used vuex-persistedstate
in my How to add Magic Link to a Nuxt.js Application guide. Check out and share your feedback.