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): should trigger watchEffect when using set to change value of array length #720

Merged
merged 1 commit into from Jun 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/reactivity/set.ts
Expand Up @@ -15,10 +15,16 @@ export function set<T>(target: any, key: any, val: T): T {
`Cannot set reactive property on undefined, null, or primitive value: ${target}`
)
}
if (isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
if (isArray(target)) {
if (isValidArrayIndex(key)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
} else if (key === 'length' && (val as any) !== target.length) {
target.length = val as any
;(target as any).__ob__?.dep.notify()
return val
}
}
if (key in target && !(key in Object.prototype)) {
target[key] = val
Expand Down
19 changes: 19 additions & 0 deletions test/v3/reactivity/set.spec.ts
@@ -0,0 +1,19 @@
import { set, ref, watchEffect } from '../../../src'

describe('reactivity/set', () => {
it('should trigger watchEffect when using set to change value of array length', () => {
const arr = ref([1, 2, 3])
const spy = jest.fn()
watchEffect(
() => {
spy(arr.value)
},
{ flush: 'sync' }
)

expect(spy).toHaveBeenCalledTimes(1)
set(arr.value, 'length', 1)
expect(arr.value.length).toBe(1)
expect(spy).toHaveBeenCalledTimes(2)
})
})