Vue · Middle · Question 3 of 75
How do you cancel a stale request when a watched id changes quickly (Vue 3.5+)?
watch(id, async (newId) => {
const controller = new AbortController();
onWatcherCleanup(() => controller.abort());
data.value = await fetch(`/api/items/${newId}`, { signal: controller.signal }).then((r) => r.json());
});- ✓Correct answer: Register cleanup with
onWatcherCleanup, which runs before the next callback and on stop - 2Watchers cancel
fetchrequests automatically - 3Use
{ deep: true }on the watcher
Explanation
Without cleanup, a slow old response can overwrite newer data. Before 3.5 the same was done with the onCleanup argument of the callback.