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

Mutation requires object reference to change #100

Open timvahlbrock opened 3 years ago

timvahlbrock commented 3 years ago

If a store has a property that is an object, a mutation only triggers updates if the reference of the property is changed. See the following example.

Using the following store.

interface FilterType {
  titleContains: string,
  organizerId: number
}

export class ContestsStore extends VuexModule {
    private filter = {} as FilterType;

    public get filterAsArray (): Parameters<ContestControllerApi['findAll']> {
        return [
            this.filter.titleContains,
            this.filter.organizerId
        ];
    }

    @mutation
    addFilter (modification: FilterType): void {
        for (const [key, value] of Object.entries(modification)) {
            this.filter[key as keyof FilterType] = value;
        }
    }
}

A watcher is created for filterAsArray, but the watcher does not update when addFilter is called, because the reference to the filter stays the same. addFilter does only cause an update when it's implemented like this.


    @mutation
    addFilter (modification: FilterType): void {
        const newFilter = Object.assign({}, this.filter);
        for (const [key, value] of Object.entries(modification)) {
            newFilter[key as keyof FilterType] = value;
        }
        this.filter = newFilter;
    }

I'm not sure whether this is a bug or intended. In case of the later one, if haven't found any documentation for this case anywhere and would like if there was a possibility to cause an update anyway.