championswimmer / vuex-module-decorators

TypeScript/ES7 Decorators to create Vuex modules declaratively
https://championswimmer.in/vuex-module-decorators/
MIT License
1.8k stars 170 forks source link

Can get state from $state but not from module #269

Open hatboysam opened 4 years ago

hatboysam commented 4 years ago

Please excuse the total n00b question, I'm just trying to understand how this is meant to be used in the most type-safe way.

I've got a module that looks like this:

@Module({
  name: "auth"
})
export default class Auth extends VuexModule {
  user: firebase.User | undefined = undefined;

  @Mutation
  setUser(u: firebase.User | null) {
    console.log(`auth.setUser(${u ? u.uid : u})`);
    this.user = u || undefined;
  }
}

I access it in my component like this:

import { Component, Prop, Vue } from "vue-property-decorator";
import { getModule } from "vuex-module-decorators";
import AuthModule from "../../store/modules/auth";

@Component({})
export default class CommentThread extends Vue {
  authModule = getModule(AuthModule, this.$store);

  mounted() {
    console.log("store.user", this.$store.state.auth.user);
    console.log("module.user", this.authModule.user);
    console.log("module.state", this.authModule.state);
  }
}

That logs out this:

store.user Object { , … }
module.user undefined
module.state undefined

What's the best way to access user from AuthModule? I'd prefer not to access it from $state because that's not typesafe.

hatboysam commented 4 years ago

Huh ok I guess undefined is no good in vue stores? Changing the module to this made it work:

export default class Auth extends VuexModule {
  public user: firebase.User | null = null;

  @Mutation
  setUser(u: firebase.User | null) {
    console.log(`auth.setUser(${u ? u.uid : u})`);
    this.user = u;
  }
}
hatboysam commented 4 years ago

Actually I'll leave this open in case some kind traveler wants to explain what happened here to me, although if the answer is just "don't use undefined" you can close it.