Skip to content

Commit

Permalink
fix(reactivity): shallowReactive map "unwraps" the nested refs
Browse files Browse the repository at this point in the history
  • Loading branch information
liuseen-l authored and sxzz committed Aug 24, 2023
1 parent 2ffe3d5 commit dfb34fd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
10 changes: 10 additions & 0 deletions packages/reactivity/__tests__/shallowReactive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ describe('shallowReactive', () => {
shallowSet.forEach(x => expect(isReactive(x)).toBe(false))
})

test('Setting a reactive object on a shallowReactive map', () => {
const msg = ref('ads')
const bar = reactive({ msg })
const foo = shallowReactive(new Map([['foo1', bar]]))
foo.set('foo2', bar)

expect(isReactive(foo.get('foo2'))).toBe(true)
expect(isReactive(foo.get('foo1'))).toBe(true)
})

// #1210
test('onTrack on called on objectSpread', () => {
const onTrackFn = vi.fn()
Expand Down
16 changes: 10 additions & 6 deletions packages/reactivity/src/collectionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ function size(target: IterableCollections, isReadonly = false) {
return Reflect.get(target, 'size', target)
}

function add(this: SetTypes, value: unknown) {
value = toRaw(value)
function add(this: SetTypes, value: unknown, isShallow = false) {
value = isShallow ? value : toRaw(value)
const target = toRaw(this)
const proto = getProto(target)
const hadKey = proto.has.call(target, value)
Expand All @@ -78,8 +78,8 @@ function add(this: SetTypes, value: unknown) {
return this
}

function set(this: MapTypes, key: unknown, value: unknown) {
value = toRaw(value)
function set(this: MapTypes, key: unknown, value: unknown, isShallow = false) {
value = isShallow ? value : toRaw(value)
const target = toRaw(this)
const { has, get } = getProto(target)

Expand Down Expand Up @@ -251,8 +251,12 @@ function createInstrumentations() {
return size(this as unknown as IterableCollections)
},
has,
add,
set,
add(this: SetTypes, value: unknown) {
return add.call(this, value, true)
},
set(this: MapTypes, key: unknown, value: unknown) {
return set.call(this, key, value, true)
},
delete: deleteEntry,
clear,
forEach: createForEach(false, true)
Expand Down

0 comments on commit dfb34fd

Please sign in to comment.