Skip to content

Commit

Permalink
fix(computed): re-calculate when object path changed
Browse files Browse the repository at this point in the history
  • Loading branch information
geekact committed Oct 15, 2023
1 parent d3e2226 commit 0c45009
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 12 deletions.
21 changes: 9 additions & 12 deletions src/reactive/ObjectDeps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,11 @@ export class ObjectDeps<T = any> implements Deps {

isDirty(): boolean {
const rootState = this.getState();

if (this.root === rootState) return false;

if (this.snapshot === this.getSnapshot(rootState)) {
this.root = rootState;
return false;
}

return true;
const { pathChanged, snapshot: nextSnapshot } = this.getSnapshot(rootState);
if (pathChanged || this.snapshot !== nextSnapshot) return true;
this.root = rootState;
return false;
}

get id(): string {
Expand All @@ -51,16 +47,17 @@ export class ObjectDeps<T = any> implements Deps {
return this.store.getState()[this.model];
}

protected getSnapshot(state: any) {
protected getSnapshot(state: any): { pathChanged: boolean; snapshot: any } {
const deps = this.deps;
let snapshot = state;

for (let i = 0; i < deps.length; ++i) {
if (!isObject<Record<string, any>>(snapshot)) break;
if (!isObject<Record<string, any>>(snapshot)) {
return { pathChanged: true, snapshot };
}
snapshot = snapshot[deps[i]!];
}

return snapshot;
return { pathChanged: false, snapshot };
}

protected proxy(currentState: Record<string, any>): any {
Expand Down
38 changes: 38 additions & 0 deletions test/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,3 +379,41 @@ test('array should always be deps', () => {
model.myData();
expect(spy).toBeCalledTimes(4);
});

test('re-calculate when path changed', () => {
const spy = vitest.fn();

const model = defineModel('re-calculate-path-changed', {
initialState: {
foo: { bar: undefined } as undefined | { bar: string | undefined },
baz: '123',
},
reducers: {
updateFoo(state, foo: undefined | { bar: string | undefined }) {
state.foo = foo;
},
},
computed: {
myData() {
const foo = this.state.foo;
spy();
return foo ? foo.bar : this.state.baz;
},
},
});

expect(model.myData()).toBeUndefined();
expect(spy).toBeCalledTimes(1);
model.updateFoo(undefined);
expect(model.myData()).toBe('123');
expect(spy).toBeCalledTimes(2);
model.updateFoo({ bar: undefined });
expect(model.myData()).toBeUndefined();
expect(spy).toBeCalledTimes(3);
model.updateFoo({ bar: 'abc' });
expect(model.myData()).toBe('abc');
expect(spy).toBeCalledTimes(4);
model.updateFoo({ bar: undefined });
expect(model.myData()).toBeUndefined();
expect(spy).toBeCalledTimes(5);
});

0 comments on commit 0c45009

Please sign in to comment.