import { onWatcherCleanup, ref, shallowRef, toValue, watch, type MaybeRefOrGetter } from "vue";
/**
* Loads data whenever its input changes, with loading and error states.
* If the input changes mid-request, the old request is aborted (Vue 3.5's
* onWatcherCleanup), so a slow old answer never overwrites a newer one.
*/
export function useAsync<I, T>(input: MaybeRefOrGetter<I>, load: (input: I, signal: AbortSignal) => Promise<T>) {
const data = shallowRef<T>();
const error = shallowRef<Error>();
const loading = ref(false);
/* Bumped by reload(), so the same input can be asked for again. */
const attempt = ref(0);
watch(
[() => toValue(input), attempt],
async ([value]) => {
const controller = new AbortController();
onWatcherCleanup(() => controller.abort());
loading.value = true;
error.value = undefined;
try {
data.value = await load(value, controller.signal);
} catch (e) {
if (!controller.signal.aborted) error.value = e as Error;
} finally {
if (!controller.signal.aborted) loading.value = false;
}
},
{ immediate: true },
);
return { data, error, loading, reload: () => attempt.value++ };
}<script setup lang="ts">
import { ref } from "vue";
import { useAsync } from "./useAsync";
/* A pretend API: slow, and it fails now and then. */
const fakeApi = (id: number, signal: AbortSignal) =>
new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => {
if (Math.random() < 0.25) reject(new Error("El servidor se ha caído"));
else resolve(`Ficha del disco nº ${id}`);
}, 400 + Math.random() * 900);
signal.addEventListener("abort", () => clearTimeout(timer));
});
const id = ref(1);
const { data, error, loading, reload } = useAsync(id, fakeApi);
</script>
<template>
<p>
<button @click="id--" :disabled="id <= 1">←</button>
Disco {{ id }}
<button @click="id++">→</button>
</p>
<p v-if="loading" class="muted">Cargando…</p>
<p v-else-if="error" class="error">{{ error.message }}. <button @click="reload">Otra vez</button></p>
<p v-else>{{ data }}</p>
</template>Disco 1
Cargando…