Open blestab opened 4 years ago
Same issue here, state is not rehydrated.
I had to implement the restoreState
function in order to get it to work, even when using localStorage
. Something like this:
// in src/store/index.ts
Vue.use(Vuex)
export interface RootState {
user: UserState
}
const vuexPersistence = new VuexPersistence<RootState>({
restoreState: (key: string, storage: Storage | undefined): RootState => {
const vuex = storage?.getItem(key) || '{}'
const json = JSON.parse(vuex)
// use the JSON to rehydrate your RootState
return {
user: {
foo: json.foo,
bar: json.bar
}
}
},
strictMode: process.env.NODE_ENV !== 'production',
})
// Declare empty store, vuex-module-decorators will register modules dynamically
const store = new Vuex.Store<RootState>({
// do not enable strict mode in prod https://vuex.vuejs.org/guide/strict.html
strict: process.env.NODE_ENV !== 'production',
plugins: [vuexPersistence.plugin],
mutations: {
RESTORE_MUTATION: vuexPersistence.RESTORE_MUTATION,
},
})
export default store
Where UserState
is something like this:
// in src/store/modules/user.ts
export interface UserState {
foo: string | null
bar: string | null
}
@Module({ dynamic: true, name: 'user', store, preserveState: localStorage.getItem('vuex') !== null })
class User extends VuexModule implements UserState {
foo: string | null
bar: string | null
// @Mutation, @Action, @MutationAction, etc go here
}
export const UserModule = getModule(User)
My code is as below:
and i can see my store persisted to local storage
But when i refresh the page my state is not restored. Am i missing something else or did I maybe do something wrong in my code?