Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(reactivity): handle Set with initial reactive values edge case #12393

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/reactivity/__tests__/reactive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,19 @@ describe('reactivity/reactive', () => {
expect(dummy).toBe(false)
})

// #8647
test('observing Set with reactive initial value', () => {
const observed = reactive({})
const observedSet = reactive(new Set([observed]))

expect(observedSet.has(observed)).toBe(true)
expect(observedSet.size).toBe(1)

// expect nothing happens
observedSet.add(observed)
expect(observedSet.size).toBe(1)
})

test('observed value should proxy mutations to original (Object)', () => {
const original: any = { foo: 1 }
const observed = reactive(original)
Expand Down
15 changes: 9 additions & 6 deletions packages/reactivity/src/collectionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,18 @@ function createInstrumentations(
}
: {
add(this: SetTypes, value: unknown) {
if (!shallow && !isShallow(value) && !isReadonly(value)) {
value = toRaw(value)
}
const target = toRaw(this)
const proto = getProto(target)
const hadKey = proto.has.call(target, value)
const valueToAdd =
!shallow && !isShallow(value) && !isReadonly(value)
? toRaw(value)
: value
const hadKey =
proto.has.call(target, valueToAdd) ||
(value !== valueToAdd && proto.has.call(target, value))
if (!hadKey) {
target.add(value)
trigger(target, TriggerOpTypes.ADD, value, value)
target.add(valueToAdd)
trigger(target, TriggerOpTypes.ADD, valueToAdd, valueToAdd)
}
return this
},
Expand Down