Vuex-persistedstate: Cannot deal with Map

Created on 1 Aug 2019  路  1Comment  路  Source: robinvdvleuten/vuex-persistedstate


Do you want to request a feature or report a bug?
feature
What is the current behavior?
My version is "vuex-persistedstate": "^2.5.4"
If my state data is a Map, when I getState, I will get an Array.

If the current behavior is a bug, please provide the steps to reproduce.

For example:

const state = {
   mapExample: new Map()
}
const getters = {
  getMapExample: state => state.mapExample
}
const mutations = {
 saveMapExample (state, payload) {
   if (payload instanceof Map) {
     state.mapExample = payload
   } else if (payload instanceof Array && payload.length === 2) {
     const [key , value] = payload
     state.mapExample.set(key, value)
  }
 }
}
  1. set: this.$store.commit('saveMapExample ', new Map([['key', 'value']]))
  2. get: const map = this.$store.getters.getMapExample
  3. use: map.get('key') // Error
  4. Actually, this map is type of Array.I should convert it by myself.const trueMap = new Map(map)

So, I write this to replace setState & getState

createPersistedState({
      storage: window.sessionStorage,
      setState (key, state, storage) {
        return storage.setItem(key, JSON.stringify(state))
      },
      getState (key, storage, value) {
        try {
          const json = (value = storage.getItem(key)) && typeof value !== 'undefined' ? JSON.parse(value) : undefined
          if (json) {
            const mapKeys = ['mapExample']
            const result = {}
            for (const [moduleKey, moduleValue] of Object.entries(json)) {
              const newState = {}
              for (const [stateKey, stateValue] of Object.entries(moduleValue)) {
                if (mapKeys.includes(stateKey)) {
                  newState[stateKey] = new Map(stateValue)
                } else {
                  newState[stateKey] = stateValue
                }
              }
              result[moduleKey] = newState
            }
            return result
          }
        } catch (err) {}
        return undefined
      }
    })

But I get an Object finally.

const map = this.$store.getters.getMapExample
// map is an Object

image

What is the expected behavior?

Expected: I will not care about the Prototype.

If this is a feature request, what is motivation or use case for changing the behavior?

When a project already has some Store datas which are Map, they can easily use this plugin.

Or is there any help that can solve this problem in the current version.

>All comments

Seems to be an issue with your application and not with this plugin. Please move the discussion Vue Forum or StackOverflow(stackoverflow.com).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kylewelsby picture kylewelsby  路  5Comments

irrg picture irrg  路  6Comments

jerometremblay picture jerometremblay  路  6Comments

metodib picture metodib  路  6Comments

joefresco picture joefresco  路  6Comments