Skip to content

Mutation requires object reference to change #100

@timvahlbrock

Description

@timvahlbrock

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions