Sometimes, we want to persist Vuex state on page refresh.
In this article, we’ll look at how to persist Vuex state on page refresh.
How to persist Vuex state on page refresh?
To persist Vuex state on page refresh, we can use the vuex-persistedstate package.
To install it, we run
npm i vuex-persistedstate
Then we use it by writing
import { Store } from "vuex";
import createPersistedState from "vuex-persistedstate";
import * as Cookies from "js-cookie";
const store = new Store({
// ...
plugins: [
createPersistedState({
getState: (key) => Cookies.getJSON(key),
setState: (key, state) =>
Cookies.set(key, state, { expires: 3, secure: true }),
}),
],
});
to call createPersistedState to return the plugin that we add to the plugins array.
We call it with an object with methods to get and set data with getState and setState respectively.
We get and set cookies when state is changed with Cookies.getJSON and Cookies.set.
Conclusion
To persist Vuex state on page refresh, we can use the vuex-persistedstate package.