championswimmer / vuex-persist

A Vuex plugin to persist the store. (Fully Typescript enabled)
http://championswimmer.in/vuex-persist
MIT License
1.67k stars 116 forks source link

First time using vuex-persist, can't get basic functionality to work #206

Open blestab opened 4 years ago

blestab commented 4 years ago

My code is as below:

import Vue from "vue";
import Vuex from "vuex";
import VuexPersist from "vuex-persist";

Vue.use(Vuex);

const vuexLocal = new VuexPersist({
  storage: window.localStorage,
});

...
const plugins = [vuexLocal.plugin];

export default new Vuex.Store({
  modules,
  state,
  mutations,
  actions,
  getters,
  plugins,
});

and i can see my store persisted to local storage

image

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?

douglasg14b commented 3 years ago

Same issue here, state is not rehydrated.

efenderbosch commented 3 years ago

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)