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());
});

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.

Further reading

Problem with a question

Vue · Middle · question 3

Test yourself

Take the Vue · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz