vuex-module-decorators icon indicating copy to clipboard operation
vuex-module-decorators copied to clipboard

Correct way to call a mutation within an action

Open souphuhn opened this issue 4 years ago • 5 comments

Hey everyone,

I have a short question, if this is a correct way to trigger a mutation within an action:

export class MyModule extends VuexModule {
   myProp: string = '';

   @Mutation
   private SET_MY_PROP(value: string) {
       this.myProp = value;
   }

   @Action
   public async setMyProp(value: string) {
      this.SET_MY_PROP(value);
   }
}

I am asking, because those get started examples commit the mutation differently like:

   @Action({ commit: 'SET_MY_PROP' })
   async setMyProp(value: string) {
      return value;
   }

or like

   @Action
   async setMyProp(value: string) {
      this.context.commit('SET_MY_PROP', value);
   }

souphuhn avatar Aug 02 '20 05:08 souphuhn

@souphuhn Personally I use the first example, calling the method instead of annotating. Reasons:

  • tooling recognizing that SET_MY_PROP is actually used (and therefore not dead code)
  • code-completion works
  • intuitive for newcomers to your project (it's just calling a class method)

One 'danger' I have noticed, is that it's tempting to use more than one argument for the mutation -- your IDE won't mind, but it won't work as expected.

// This won't work
export class MyModule extends VuexModule {
   myProp: string = '';

   @Mutation
   private SET_MY_PROP(value1: string, value2: string) {
       this.myProp = value1 + value2;
   }

   @Action
   public async setMyProp(value: string) {
      this.SET_MY_PROP('hello', value);
   }
}
// This will
export class MyModule extends VuexModule {
   myProp: string = '';

   @Mutation
   private SET_MY_PROP([value1, value2]: [string, string]) {
       this.myProp = value1 + value2;
   }

   @Action
   public async setMyProp(value: string) {
      this.SET_MY_PROP(['hello', value]);
   }
}

EtienneBruines avatar Aug 03 '20 15:08 EtienneBruines

I also ask myself the same question every time and seems no one could explain why the examples are using the latter approach. Maybe this is a "bug" that works? IMHO, this issue should have more attention from the community because if the former approach is indeed a feature it should be the one present in the doc examples

Pacheco95 avatar Apr 14 '21 19:04 Pacheco95

@championswimmer could you provide some explanation here?

Pacheco95 avatar Apr 14 '21 20:04 Pacheco95

I'd like to know the other way to call commit or disptach instead of calling via this.context

bdockbockd avatar Apr 18 '21 16:04 bdockbockd

@bdockbockd just call your mutations from your actions like normal method calls

Pacheco95 avatar Apr 18 '21 22:04 Pacheco95