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(watchEffect): prevent recursive calls when using flush:sync #389

Merged
merged 3 commits into from Jun 19, 2020
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: 13 additions & 1 deletion src/apis/watch.ts
Expand Up @@ -230,7 +230,19 @@ function createWatcher(

// effect watch
if (cb === null) {
const getter = () => (source as WatchEffect)(registerCleanup)
let running = false
const getter = () => {
// preventing the watch callback being call in the same execution
if (running) {
return
}
try {
running = true
;(source as WatchEffect)(registerCleanup)
} finally {
running = false
}
}
const watcher = createVueWatcher(vm, getter, noopFn, {
deep: options.deep || false,
sync: isSync,
Expand Down
18 changes: 18 additions & 0 deletions test/v3/runtime-core/apiWatch.spec.ts
Expand Up @@ -514,4 +514,22 @@ describe('api: watch', () => {
// expect(spy).toHaveBeenCalledTimes(1);
// expect(warnSpy).toHaveBeenCalledWith(`"deep" option is only respected`);
// });


// #388
it('should not call the callback multiple times', () => {
const data = ref([1, 1, 1, 1, 1])
const data2 = ref<number[]>([])

watchEffect(
() => {
data2.value = data.value.slice(1, 2)
},
{
flush: 'sync',
}
)

expect(data2.value).toMatchObject([1])
})
})