vue.joedoe.dev

← All the recipesComposablesVue 3.5+

Load data without crossed answers

Loading, error and data in one composable. If you switch record before the answer arrives, the old request is cancelled with onWatcherCleanup. Click through quickly.

TypeScript
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++ };
}

Disco 1

Cargando…

↑↓ move · ↵ open · esc close