Vue 3 Data Fetching with Composables
Fetch data in Vue 3 using composables with reactive loading states, error handling, automatic refetch on parameter change, and cleanup on component unmount.
Code
import { ref, watchEffect, onUnmounted } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(false);
let controller;
watchEffect(async () => {
controller?.abort();
controller = new AbortController();
loading.value = true;
try {
const res = await fetch(url.value, { signal: controller.signal });
data.value = await res.json();
} catch (e) {
if (e.name !== 'AbortError') error.value = e;
} finally {
loading.value = false;
}
});
onUnmounted(() => controller?.abort());
return { data, error, loading };
}How the snippet works
Structurally, expect the function useFetch and nothing else.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. From vue it pulls ref, watchEffect, onUnmounted — the imports name exactly which library surface the snippet touches.
The result comes back as an object carrying data, error.
Points of care
- External dependency:
vue— install it before running the snippet. - Uses
fetch, so it needs a browser context — it will not run as-is in Node without shims.
Applying it
Signature: export function useFetch(url)
useFetch is the public entry point; everything else in the file exists to support it.
The call returns data, error — destructure what you need at the call site.
Statements that matter
onUnmounted(() => controller?.abort());
const res = await fetch(url.value, { signal: controller.signal });
controller = new AbortController();
FAQ
- Does `useFetch` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Do I need to install anything before running this?
- Yes: `vue` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.