Vuex access modules state in from store

Viewed 430

I have a Vuex store that is split up into multiple modules. Each of these modules has it's own state.

I cannot seem to get this to work I always get an error stating that Uncaught (in promise) TypeError: Cannot read property 'state' of undefined. I don't know what I do wrong.

This is the index.js of my Vue store:

import { createStore } from 'vuex';

import layers from './modules/layers';

export const store = createStore({
  modules: {
    layers,
  },
});

This is the module I am trying to access:

export default {
  namespaced: true,
  state: {
      areas: [],
  },
  mutations: {},
  actions: {},
  modules: {},
  getters: {},
};

Here I try to access the state that is being defined:

import { useStore } from 'vuex';

export default function useAddExistingFeatures() {
  const store = useStore();
  const area = store.layers.state.areas[1];
}

My main.js. The plugins.js is just a file to load my css files.

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { store } from './store';

import './plugins';

createApp(App).use(store).use(router).mount('#app');
1 Answers

You should get access to the state field before the module name :

const area = store.state.layers..areas[1];

instead of const area = store.layers.state.areas[1];

Related