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

@Action and separate @Mutation always fails #283

Open jfdoolster opened 4 years ago

jfdoolster commented 4 years ago

@championswimmer,

I am a big fan of this vuex-module-decorators package. It is straight forward and easy to work with and has really helped me learn vue and typescript, greatly improving my apps.

However, I have consistently gotten an error when trying to work with vuex store. Weeks of looking through the documentation and issue trackers has not helped me fix it. I'm hoping that you can provide some insight.

MWE:

I create the module:

// store/modules/user.ts
import { VuexModule, Module, Mutation, Action } from 'vuex-module-decorators'
import store from '@/store'; // @/store/index.ts

@Module({name: 'User', store, namespaced: true })
export default class User extends VuexModule {
  public name = 'John Smith'

  @Mutation
  public setName(newName: string): void {
    this.name = newName
  }
  @Action({rawError: true})
  public updateName(newName: string): void {
    this.context.commit('setName', newName)
  }
}

Register it in my vuex store:

// @/store/index.ts
import Vue from "vue";
import Vuex from "vuex";
import User from "@/store/modules/User";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    User
  }
});

The issue comes when I try to the module's Action in a component:

// @/components/Test.vue  (<script> tag contents)
import { Component, Prop, Vue } from 'vue-property-decorator';
import { namespace } from 'vuex-class';
const user = namespace('User');

@Component
export default class Test extends Vue {

  @user.State public name!: string;

  @user.Action public updateName!: (newName: string) => void;
}

Every time I try to call the updateName Action inside the component, I get the error: "Error: ERR_STORE_NOT_PROVIDED: To use getModule(), either the module should be decorated with store in decorator, i.e. @Module({store: store}) or store should be passed when calling getModule(), i.e. getModule(MyModule, this.$store)"

I am passing the store to the @Module in src/store/modules/User.ts, but perhaps not correctly?

this example is extremely similar to many tutorials I have found. I do not understand why this simple example is not running correctly...

Note: I have had some success working with @MutationAction, but there are still issues with that and I prefer using @Mutation and @Action separately.

Thanks for you help!

Pacheco95 commented 3 years ago

Hi @jfdoolster! Try to make the action an async function.

Pacheco95 commented 3 years ago

And make sure your store is being initialized before your modules