javascript / intermediate
Snippet
Handling Request Cancellation in Asynchronous Composables Using AbortController
When triggering asynchronous network requests based on reactive state changes, rapid input can cause race conditions where outdated responses overwrite newer data. Integrating JavaScript's native AbortController within watchEffect cancels pending requests before new ones initiate.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { ref, watchEffect, onUnmounted } from 'vue';export function useFetchUser(userIdRef) {const userData = ref(null);let controller = null;watchEffect(async () => {if (controller) controller.abort();controller = new AbortController();try {const response = await fetch(`/api/users/${userIdRef.value}`, {signal: controller.signal});userData.value = await response.json();} catch (err) {if (err.name !== 'AbortError') throw err;}});onUnmounted(() => controller?.abort());return { userData };}
vue
Breakdown
1
if (controller) controller.abort();
Cancels the previous pending HTTP request signal before firing a new network operation.
2
controller = new AbortController();
Instantiates a fresh AbortController instance providing a distinct cancellation signal.
3
signal: controller.signal
Binds the Fetch API call to the controller signal so the browser aborts the request immediately upon demand.
4
if (err.name !== 'AbortError') throw err;
Filters out expected AbortError instances to avoid treating intentional request cancellations as application failures.
5
onUnmounted(() => controller?.abort());
Ensures any in-flight request is cancelled when the consuming component is unmounted from the DOM.