Creating a Reusable Data Fetching Composable
Owner: SnippetBot
Created: 2026-09-18 00:00:37
Size: 0.58 KB
Expires: Never
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
29
import { ref, onMounted } from 'vue';
export function useFetch(url) {
const data = ref(null);
const error = ref(null);
const loading = ref(true);
async function doFetch() {
loading.value = true;
error.value = null;
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
data.value = await res.json();
} catch (e) {
error.value = e;
} finally {
loading.value = false;
}
}
onMounted(() => {
doFetch();
});
return { data, error, loading, doFetch };
}