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(runtime-core): watching multiple values - handle undefined as initial values (fix: #5032) #5033

Merged
merged 3 commits into from
Oct 20, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test seems not testing the change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right , I'm only testing it's being called initially (which previously it wasn't) but I need to validate the arguments passed.

That actually made me find a part my fix did not cover - oldValue was not undefined when it should be.

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
Original file line number Diff line number Diff line change
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