Search code examples
vue.jsvuex

vuex persisted state: Storing class instances. Any best practices?


Both vuex-persist or vuex-persistedstate store state in localStorage using JSON.stringify. This means all functions of an object are stripped off. In case the object is a class instance this means the instance cannot automatically be restored. Imho this is problematic since application state often consists of class instances.

I'm not sure how to proceed. My vuex state consist mainly of class instances. What is the best practice regarding persistable state?


Solution

  • All packages that uses the browser storage are limited on how the storage works. Session storage or local storage consists of a key/value pair value

    To solve a problem like this you would have to unserialize the data when the application is initialized.

    A fairly simple example to what you are trying to achieve:

    Let's say you have a class of User

    class User {
      constructor(name) {
        this.name = name;
      }
     
      greetings() {
        console.log(`Hello ${this.name}`)
      }
    }
    

    and you have an array of users in your store and it is persisted to your localstorage:

    const state = {
      users: [User, User, User]
    }
    

    You can now leverage the plugins in Vuex:

    const userSerializer = (store) => {
       const serializedUsers = store.users.map(u => new User(u.name));
    
       // you would have to define this mutation
       store.commit('setUsers', serializedUsers)
    }