Skip to content

Commit

Permalink
fix(runtime-core): watching multiple values - handle undefined as i…
Browse files Browse the repository at this point in the history
…nitial values (fix: #5032) (#5033)
  • Loading branch information
LinusBorg committed Oct 20, 2022
1 parent 9617dd4 commit bc167b5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
17 changes: 17 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Expand Up @@ -177,6 +177,23 @@ describe('api: watch', () => {
])
})

it('watching multiple sources: undefined initial values and immediate: true', async () => {
const a = ref()
const b = ref()
let called = false
watch(
[a, b],
(newVal, oldVal) => {
called = true
expect(newVal).toMatchObject([undefined, undefined])
expect(oldVal).toBeUndefined()
},
{ immediate: true }
)
await nextTick()
expect(called).toBe(true)
})

it('watching multiple sources: readonly array', async () => {
const state = reactive({ count: 1 })
const status = ref(false)
Expand Down
9 changes: 7 additions & 2 deletions packages/runtime-core/src/apiWatch.ts
Expand Up @@ -296,7 +296,9 @@ function doWatch(
return NOOP
}

let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE
let oldValue: any = isMultiSource
? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE)
: INITIAL_WATCHER_VALUE
const job: SchedulerJob = () => {
if (!effect.active) {
return
Expand All @@ -323,7 +325,10 @@ function doWatch(
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
newValue,
// pass undefined as the old value when it's changed for the first time
oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
oldValue === INITIAL_WATCHER_VALUE ||
(isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
? undefined
: oldValue,
onCleanup
])
oldValue = newValue
Expand Down

0 comments on commit bc167b5

Please sign in to comment.