0 day streak
javascript / expert
Snippet

Auto-Aborting Async Composables

Expert async management in Vue involves handling race conditions. By using the 'onCleanup' callback inside a watcher, we can abort pending fetch requests via AbortController whenever the source URL changes, ensuring only the latest request's data is applied.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { ref, watch, toValue } from 'vue';
export function useAsyncData(urlSource) {
const data = ref(null);
watch(() => toValue(urlSource), async (url, oldUrl, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort());
try {
const response = await fetch(url, { signal: controller.signal });
data.value = await response.json();
} catch (e) {
if (e.name !== 'AbortError') console.error(e);
}
}, { immediate: true });
return { data };
}
vue
Breakdown
1
onCleanup(() => controller.abort())
Executes before the watcher re-runs or the component unmounts.
2
toValue(urlSource)
Normalizes refs or getters into their raw values for tracking.