Why am I getting "rawModule is undefined" when adding Vuex modules?
Asked Answered
F

2

6

I recently was struggling with implementing modules in Vuex for the first time. I couldn't find much info on the console error message I was getting ( rawModule is undefined ), so I thought I'd share the issue I ran into and the solution. I was doing a quick, simple version of a module implementation as I was working through some examples:

export const store = new Vuex.Store({
  state: {
    loggedIn: false,
    user: {},
    destination: ''
  },
  mutations: {
    login: state => state.loggedIn = true,
    logout: state => state.loggedIn = false,
    updateUser: ( state, user ) => { state.user = user },
    updateDestination: ( state, newPath ) => { state.destination = newPath }
  },
  modules: {
    project
  },
});

const project = {
  state: {}
}
Felske answered 2/2, 2018 at 19:58 Comment(0)
F
5

The issue ultimately was that I had declared my module after I tried to add it to the Vuex store. I had thought it would have been okay to declare the module later thanks to variable hoisting, but that doesn't appear to be the case. Here is the code that does work:

const project = {
  state: {}
}

export const store = new Vuex.Store({
  state: {
    loggedIn: false,
    user: {},
    destination: ''
  },
  mutations: {
    login: state => state.loggedIn = true,
    logout: state => state.loggedIn = false,
    updateUser: ( state, user ) => { state.user = user },
    updateDestination: ( state, newPath ) => { state.destination = newPath }
  },
  modules: {
    project
  },
});

Hopefully this saves some people some time. I didn't see anything in the documentation requiring a certain ordering, so I'm surprised it mattered. If anyone has some insight into why it works this way, I'd be really interested in hearing it! Perhaps because the Vuex.Store() function gets called before the project value is set, so the project module's value is encapsulated as undefined, and that causes the error?

Felske answered 2/2, 2018 at 19:58 Comment(0)
A
1

If you have using class components, put the store import before the module import, Eg:

// This is wrong
import { getModule } from "vuex-module-decorators";
import AppModule from "@/store/app-module";
import store from "@/store";

const appModule = getModule(AppState, store);
// This work
import { getModule } from "vuex-module-decorators";
import store from "@/store"; // Before first
import AppModule from "@/store/app-module"; // Then import the module

const appModule = getModule(AppState, store);
Autolysis answered 2/10, 2021 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.