javascript / intermediate
Snippet
Handling Fetch Cancellation with AbortController in Vue Composables
Using JavaScript's native AbortController in asynchronous Vue composables prevents race conditions and memory leaks by canceling pending HTTP requests when new ones start or when the component scope is destroyed.
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
24
25
26
27
28
import { ref, onScopeDispose } from 'vue';export function useFetchWithAbort(url) {const data = ref(null);const loading = ref(false);let controller = null;async function execute() {if (controller) controller.abort();controller = new AbortController();loading.value = true;try {const response = await fetch(url, { signal: controller.signal });data.value = await response.json();} catch (err) {if (err.name !== 'AbortError') throw err;} finally {loading.value = false;}}onScopeDispose(() => {if (controller) controller.abort();});return { data, loading, execute };}
vue
Breakdown
1
if (controller) controller.abort();
Aborts any ongoing fetch request before initiating a new one.
2
const response = await fetch(url, { signal: controller.signal });
Passes the AbortSignal to the fetch API to bind cancellation to the controller.
3
if (err.name !== 'AbortError') throw err;
Ignores deliberate AbortError exceptions while allowing actual network errors to bubble up.
4
onScopeDispose(() => { if (controller) controller.abort(); });
Ensures active requests are canceled automatically when the component unmounts.