A watcher is useful when a reactive value must synchronize with something outside Vue, such as a network request. It is not needed to copy a computed value into another ref. When a selected case changes, the old fetch may finish after the new one and overwrite the correct detail. The watcher must own both the request and its invalidation cleanup. Aborting an HTTP request is helpful, but it is not an authority check: a response may already be delivered or a downstream operation may continue. A generation guard ensures that only the current selection publishes data. Cleanup should be registered before asynchronous work yields, so a rapid selection change has a cancellation path from the start.
Vue Watch Cleanup and Stale Request Ownership
Working case
A reviewer opens case 47, then immediately opens case 81. The first detail request is slow and returns last. Without cleanup, the panel heading says 81 while the body shows case 47's confidential note. The team watches the selected ID, creates one controller and generation for each run, registers cleanup immediately, and clears the old detail while loading the new one. A result may publish only if it still owns the current generation and case ID. The server also checks case-level authorization on each request; no frontend cancellation rule grants access. When the component unmounts, the watcher stops and its active request is cleaned up.
Implementation boundary
import { ref, watch } from "vue";
export function usePermitDetail(selectedCaseId) {
const detail = ref(null);
const error = ref(null);
let generation = 0;
watch(selectedCaseId, (caseId, _previous, onCleanup) => {
const activeGeneration = ++generation;
const controller = new AbortController();
onCleanup(() => {
controller.abort();
if (generation === activeGeneration) generation++;
});
detail.value = null;
error.value = null;
if (caseId === null) return;
fetch(`/api/permits/${encodeURIComponent(caseId)}`, { signal: controller.signal })
.then(async (response) => {
if (!response.ok) throw new Error(`Permit detail failed: ${response.status}`);
const payload = await response.json();
if (!payload || String(payload.id) !== String(caseId)) throw new Error("Unexpected permit detail");
return payload;
})
.then((payload) => { if (activeGeneration === generation && selectedCaseId.value === caseId) detail.value = payload; })
.catch((failure) => { if (failure.name !== "AbortError" && activeGeneration === generation) error.value = failure; });
}, { immediate: true });
return { detail, error };
}Watch a specific reactive source rather than an entire mutable object whose incidental fields change. In the callback, allocate an AbortController and register the cleanup synchronously using the watch callback's cleanup argument. Increment or capture a generation token before starting the fetch. Mark the detail pending and clear or explicitly label the previous content so the UI cannot misattribute it. After the response and parse, check the current generation and selected ID before assigning the result; treat an abort as cancellation, not as an error banner. Handle HTTP errors and malformed payloads separately, because fetch only rejects for transport failures and cancellation. If requests depend on account identity as well as case ID, watch both and invalidate when either changes. Use a server-owned permission check for private data. Test rapid selection, logout, unmount, and network failures.
Cost and boundaries
One watcher creates at most one active request per selection in the ordinary path, but rapid selection can start several requests before abort propagates. A generation counter is O(1) state and comparison; its purpose is correctness, not server work cancellation. Aborting may save bandwidth and browser parsing yet cannot roll back a server-side mutation. Keeping previous detail visible reduces flicker but risks showing the wrong record unless it is clearly labeled. Clearing it avoids ambiguity but creates a loading interval. Measure request count, aborted bytes where available, stale-result rejections, and time to current detail; avoid logging private note content to diagnose a race.
Failure trace
Delay case 47 until after case 81 returns and ensure case 47 cannot publish. Switch 47 to 81 to 62 quickly, then unmount; every old request should be invalidated, even if a mock ignores abort. Sign out while case 62 is loading and verify the result cannot enter the next user's view. Return a 403 for one case and a malformed successful body for another; neither should be mistaken for a generic offline failure. Try a response that completes just before cleanup and verify the generation check still reflects the current selection. Confirm that the watcher does not refetch because a presentational field changed.
Verification
- A stale request cannot publish after selection changes.
- Cleanup is registered before asynchronous work begins.
- HTTP, transport, abort, and invalid-payload failures remain distinct.
Practice drill
Build a detail loader for selected cases 47, 62, and 81. Script response delays of 620, 81, and 47 milliseconds, then select them in that order. Record start, cleanup, abort, parse, and publication for each generation. State what the panel displays while pending and after 403, transport failure, and sign-out. Run the same sequence with an abort-ignoring transport stub; the final body must still belong to the final selected case. Count duplicate requests caused by watching a broad object rather than just identity fields.
Decision note
A watcher owns external work and its cleanup; the current identity alone may publish a result.
Common Mistakes
- Using abort as the only stale-result guard.
- Watching broad mutable state and refetching on irrelevant changes.
- Leaving old private detail under a new case heading.
Related lessons
Vue Reactivity and Component Boundaries; Vue Source State, Computed Views, and Large Snapshots; Vue Props, Emits, and Keyed Editor Ownership; Vue Server Rendering and Hydration Stability; Fetch requests: separate HTTP failure, transport failure, and cancellation; Authorization and Tenant Boundaries.
Apply and check
Build Project: Vue permit review queue and review Web Development: Vue reactivity and boundaries quiz.
