Skip to content

Commit 5e44eeb

Browse files
skirtles-codeJohnnyEvoJohnny Charcosset
authored
Immediate watchers with the Composition API (#2144)
* Update: watchers.md Add `Eager Watchers` section to composition side * docs: returns consideration * Reword the section on watchEffect Co-authored-by: Johnny Charcosset <[email protected]> Co-authored-by: Johnny Charcosset <[email protected]>
1 parent 10bfe93 commit 5e44eeb

File tree

1 file changed

+33
-17
lines changed

1 file changed

+33
-17
lines changed

src/guide/essentials/watchers.md

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -220,12 +220,12 @@ watch(
220220
Deep watch requires traversing all nested properties in the watched object, and can be expensive when used on large data structures. Use it only when necessary and beware of the performance implications.
221221
:::
222222

223-
<div class="options-api">
224-
225-
## Eager Watchers \* {#eager-watchers}
223+
## Eager Watchers {#eager-watchers}
226224

227225
`watch` is lazy by default: the callback won't be called until the watched source has changed. But in some cases we may want the same callback logic to be run eagerly - for example, we may want to fetch some initial data, and then re-fetch the data whenever relevant state changes.
228226

227+
<div class="options-api">
228+
229229
We can force a watcher's callback to be executed immediately by declaring it using an object with a `handler` function and the `immediate: true` option:
230230

231231
```js
@@ -245,41 +245,57 @@ export default {
245245
```
246246

247247
The initial execution of the handler function will happen just before the `created` hook. Vue will have already processed the `data`, `computed`, and `methods` options, so those properties will be available on the first invocation.
248+
249+
</div>
250+
251+
<div class="composition-api">
252+
253+
We can force a watcher's callback to be executed immediately by passing the `immediate: true` option:
254+
255+
```js
256+
watch(source, (newValue, oldValue) => {
257+
// ...
258+
}, { immediate: true })
259+
```
260+
248261
</div>
249262

250263
<div class="composition-api">
251264

252265
## `watchEffect()` \*\* {#watcheffect}
253266

254-
`watch()` is lazy: the callback won't be called until the watched source has changed. But in some cases we may want the same callback logic to be run eagerly - for example, we may want to fetch some initial data, and then re-fetch the data whenever relevant state changes. We may find ourselves doing this:
267+
It is common for the watcher callback to use exactly the same reactive state as the source. For example, consider the following code, which uses a watcher to load a remote resource whenever the `todoId` ref changes:
255268

256269
```js
257-
const url = ref('https://...')
270+
const todoId = ref(1)
258271
const data = ref(null)
259272

260-
async function fetchData() {
261-
const response = await fetch(url.value)
273+
watch(todoId, async () => {
274+
const response = await fetch(
275+
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
276+
)
262277
data.value = await response.json()
263-
}
264-
265-
// fetch immediately
266-
fetchData()
267-
// ...then watch for url change
268-
watch(url, fetchData)
278+
}, { immediate: true })
269279
```
270280

271-
This can be simplified with [`watchEffect()`](/api/reactivity-core.html#watcheffect). `watchEffect()` allows us to perform a side effect immediately while automatically tracking the effect's reactive dependencies. The above example can be rewritten as:
281+
In particular, notice how the watcher uses `todoId` twice, once as the source and then again inside the callback.
282+
283+
This can be simplified with [`watchEffect()`](/api/reactivity-core.html#watcheffect). `watchEffect()` allows us to track the callback's reactive dependencies automatically. The watcher above can be rewritten as:
272284

273285
```js
274286
watchEffect(async () => {
275-
const response = await fetch(url.value)
287+
const response = await fetch(
288+
`https://jsonplaceholder.typicode.com/todos/${todoId.value}`
289+
)
276290
data.value = await response.json()
277291
})
278292
```
279293

280-
Here, the callback will run immediately. During its execution, it will also automatically track `url.value` as a dependency (similar to computed properties). Whenever `url.value` changes, the callback will be run again.
294+
Here, the callback will run immediately, there's no need to specify `immediate: true`. During its execution, it will automatically track `todoId.value` as a dependency (similar to computed properties). Whenever `todoId.value` changes, the callback will be run again. With `watchEffect()`, we no longer need to pass `todoId` explicitly as the source value.
295+
296+
You can check out [this example](/examples/#fetching-data) of `watchEffect()` and reactive data-fetching in action.
281297

282-
You can check out [this example](/examples/#fetching-data) with `watchEffect` and reactive data-fetching in action.
298+
For examples like these, with only one dependency, the benefit of `watchEffect()` is relatively small. But for watchers that have multiple dependencies, using `watchEffect()` removes the burden of having to maintain the list of dependencies manually. In addition, if you need to watch several properties in a nested data structure, `watchEffect()` may prove more efficient than a deep watcher, as it will only track the properties that are used in the callback, rather than recursively tracking all of them.
283299

284300
:::tip
285301
`watchEffect` only tracks dependencies during its **synchronous** execution. When using it with an async callback, only properties accessed before the first `await` tick will be tracked.

0 commit comments

Comments
 (0)