From 22d7a1cc949ec100b291731b9d9499bef469cdb3 Mon Sep 17 00:00:00 2001 From: geekact Date: Sat, 14 Oct 2023 17:31:21 +0800 Subject: [PATCH] fix(computed): update array data fail to re-calculate used fields --- src/reactive/ObjectDeps.ts | 8 ++++++-- test/computed.test.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/reactive/ObjectDeps.ts b/src/reactive/ObjectDeps.ts index a048e2c..279498d 100644 --- a/src/reactive/ObjectDeps.ts +++ b/src/reactive/ObjectDeps.ts @@ -59,11 +59,15 @@ export class ObjectDeps implements Deps { } protected proxy(currentState: Record): any { - if (currentState === null || !isObject>(currentState)) { + if ( + currentState === null || + !isObject>(currentState) || + Array.isArray(currentState) + ) { return currentState; } - const nextState: object | any[] = Array.isArray(currentState) ? [] : {}; + const nextState = {}; const keys = Object.keys(currentState); const currentDeps = this.deps.slice(); let visited = false; diff --git a/test/computed.test.ts b/test/computed.test.ts index d869b3f..a9e265e 100644 --- a/test/computed.test.ts +++ b/test/computed.test.ts @@ -345,3 +345,37 @@ test('complex parameter can not hit cache', () => { expect(spy).toBeCalledTimes(2); spy.mockRestore(); }); + +test('array should always be deps', () => { + const spy = vitest.fn(); + + const model = defineModel('computed-from-array', { + initialState: { + x: [{ foo: 'bar' } as { foo: string; other?: string }], + y: {}, + }, + reducers: { + update(state, other: string) { + state.x = [{ foo: 'bar' }, { foo: 'baz', other }]; + }, + }, + computed: { + myData() { + spy(); + return this.state.x.filter((item) => item.foo === 'bar'); + }, + }, + }); + + model.myData(); + expect(spy).toBeCalledTimes(1); + model.update('baz'); + model.myData(); + expect(spy).toBeCalledTimes(2); + model.update('x'); + model.myData(); + expect(spy).toBeCalledTimes(3); + model.update('y'); + model.myData(); + expect(spy).toBeCalledTimes(4); +});