robinvdvleuten / vuex-persistedstate

💾 Persist and rehydrate your Vuex state between page reloads.
https://npm.im/vuex-persistedstate
MIT License
5.77k stars 378 forks source link

Handling key removal/addition/rename #397

Open palfaro91 opened 3 years ago

palfaro91 commented 3 years ago

Relevant code or config

What you did: I renamed a key in my state What happened: App crashed because the updated key didn't exist in localstorage state

Reproduction sandbox:

Problem description: I renamed one key in my state definition and since the state was loaded from local storage the new key was not in the state. What's the proper way of updating a key name? for example my state definition originally looked like this

export const state  = () => ({
  foo: {
    user: {
      first_name: '',
    }
  }
})

so my local storage looked like { foo: {user: { first_name: '' } } }

i then updated my state definition to

export const state  = () => ({
  foo: {
    account: {
      first_name: '',
    }
  }
})

and references to foo.user.first_name were updated to foo.account.first_name. My app crashes here because state still has foo.user. How do i go about updating my local storage state so that it has the new key? Suggested solution:

Harm-Nullix commented 2 years ago

You could use something like getState and then transforming it yourself:

getState(storage) {
    if (storage.foo?.user) {
        storage.foo.account = Object.assign({}, storage.foo.user)
        delete storage.foo.user
    }
   return storage
}

(not tested)