Skip to content

Commit

Permalink
fix(watchEffect): prevent recursive calls when using flush:sync (#389)
Browse files Browse the repository at this point in the history
* fix(watchEffect): prevent recursive calls when using `flush:sync`

* chore: better comment
  • Loading branch information
pikax committed Jun 19, 2020
1 parent 233dafa commit f7f1e77
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
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])
})
})

0 comments on commit f7f1e77

Please sign in to comment.