Using a Map inside of Vuex state

Viewed 5492

I'm building a prototype module to learn about Vuex and running into what seems like a simple issue -- I'm having trouble using a Map as one of my state variables.

I want to use Vuex to store some basic user preferences across multiple modules and figured a Map would be a simple way to do it since the prefs could be handled as simple key/value pairs. But I'm either not defining the Map correctly, or I'm not using it correctly within the mutations.

<script lang="ts">
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userSettings: Map,
  },
  mutations: {
    addUserSetting(state, payload) {
      if (state.userSettings == null) {
        state.userSettings = new Map();
      }
      state.userSettings.set(payload.key, payload.value);
    }

  },

})


</script>

I'd be willing to use another object, and I started with an array of UserPref objects but that didn't go well, either.

1 Answers

Vue 2 doesn't have proper support for Map.

Assuming your keys are strings I suggest using an Object instead. To get a totally empty object (with no inherited properties, not even toString) you can use Object.create(null), or just use a normal object using {} if that seems unnecessary.

e.g.

import Vue from 'vue'

export default new Vuex.Store({
  state: {
    userSettings: Object.create(null),
  },
  mutations: {
    addUserSetting(state, payload) {
      Vue.set(state.userSettings, payload.key, payload.value);
    }
  }
})

Vue.set must be used as the properties are being added.

Related