michaelolof / vuex-class-component

A Type Safe Vuex Module or Store Using ES6 Classes and ES7 Decorators written in TypeScript.
217 stars 21 forks source link

[v2.0.4] Component breaks if no explicit mutation is defined #45

Closed saniales closed 5 years ago

saniales commented 5 years ago

Hello, thanks for the work you are doing. I am writing to signal an easily fixable bug of the component.

How to reproduce

Create a vuex class component with no mutations, in my particular case the component had the following code:

class MyComponent extends {
  private authData: any;

  get tokenData() : Auth0DecodedHash | null {
      return this.authData;
  }

  set tokenData(authData: Auth0DecodedHash | null) {
    if (authData) {
      this.authData = authData;
      localStorage.setItem("token", JSON.stringify(authData));
    } else {
      localStorage.removeItem("token");
    }
  }

  @action async login(): Promise<void> {
    try {
      const authData = await this.handleAuthentication() // PLACEHOLDER
      if (authData) {
        this.tokenData = authData;
      }
    } catch (error) {
      handleError(error); // PLACEHOLDER
    }
  }

  private async handleAuthentication(): Promise<any> {
    // perform authentication handling
  }
}

by serving your application your application should break (assuming you added correctly the module to the vuex store.

In particular, thanks to the chrome debugger I found out where is the problem:

// If prototype field is an explicit mutation
var fieldIsExplicitMutation = (typeof descriptor.value === "function" &&
  explicitMutationNames.indexOf(field) > -1); // BREAKS HERE
if (fieldIsExplicitMutation) {
  var mutation = function (state, payload) { return descriptor.value.call(state, payload); };
  explicitMutations[field] = mutation;
  return "continue";
}

Workaround

Just add a dummy mutation

class MyComponent extends {
  // ...
  @mutation dummy() : void {
    throw new Error("Should never call this method, it is a workaround");
  }
}

Actual Fix

note that if explicitMutations is an empty object explicitMutationNames is undefined, therefore, adding an additional check would make this error disappear. I would revise how the explicitMutationNames array is created anyway.

Thank you :+1:

michaelolof commented 5 years ago

Hello @saniales

Apologies for the late reply I believe this should fix your issue

https://github.com/michaelolof/vuex-class-component/blob/master/src/module.ts#L143

You can upgrade to v2.0.6