championswimmer / vuex-persist

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

Inverse Reducer #158

Open Dabnis opened 4 years ago

Dabnis commented 4 years ago

While you have the reducer property, we have to list ALL parts of the state that we want to persist. In my situation of a complex store with many modules & I only need to stop 2-3 pieces of state data from being persisted it means that I have a lot of code to write for the reducer just so I can show what is to be persisted.

A much better approach (for me) would be a reducer that signifies what I DO NOT want to persist.

Is this an easy addition?

Nikey646 commented 4 years ago

Not sure if this will help you, but i wanted the capability to blacklist parts of a store, from the store itself. I did this via adding a "blacklist" property to each module's state, and then used this reducer (Assuming lodash is available for cloneDeep)

const blacklistReducer = state => {
  const filtered = cloneDeep(state)

  for (const key in state) {
    if (state.hasOwnProperty(key) && state[key]["blacklist"]) {
      const blacklist = state[key]["blacklist"];
      if (blacklist[0] === "*") {
        delete filtered[key]
        continue;
      }

      blacklist.forEach(blacklistKey => {
        delete filtered[key][blacklistKey]
      })
      delete filtered[key]["blacklist"]
    }
  }

  return filtered
}

The deep clone is required to prevent the delete filtered[key]* from removing data from the vuex state. An alternative way of doing this would be looping through all the keys on the provided state, and if it's not black listed, add it to a new object and return that object, meaning there is no mutation against the state, nor is there needless cloning of what will be deleted later.