import type { Ref, WatchSource } from 'vue'; import { ref, shallowRef, watch } from 'vue'; /** Reactive async-data snapshot: current data, loading, and error. */ export interface AsyncData { /** Latest successful result. Kept visible during a refetch. */ data: Ref; /** True while a fetch for the current args is in flight. */ loading: Ref; /** Error message from the most recent failed fetch, else null. */ error: Ref; } /** * Runs an async `fetcher` immediately and again whenever `source` changes, * exposing the result as reactive refs. Stale responses (the source changed * during a fetch, or the component unmounted) are dropped via a generation * counter, so only the latest in-flight request can write state. * * The Vue analogue of the React `useAsyncData` hook and the Angular * `createAsyncData` helper: the state shape (`data` / `loading` / `error`) is * identical so pages port across frameworks unchanged. * * @typeParam TArgs - The reactive arguments passed to the fetcher. * @typeParam T - The fetched result type. * @param source - Reactive source (ref, getter, or array of them) whose value * is forwarded to `fetcher`. Re-runs on change. * @param fetcher - Async function producing the data for the current args. * @returns Reactive `{ data, loading, error }` refs. */ export function useAsyncData( source: WatchSource, fetcher: (args: TArgs) => Promise ): AsyncData { const data = shallowRef(null); const loading = ref(true); const error = ref(null); let generation = 0; const run = (args: TArgs): void => { const current = ++generation; loading.value = true; error.value = null; fetcher(args) .then(result => { if (current === generation) { data.value = result; } }) .catch((err: unknown) => { console.error(err); if (current === generation) { error.value = err instanceof Error ? err.message : 'An error occurred'; } }) .finally(() => { if (current === generation) { loading.value = false; } }); }; watch(source, args => run(args), { immediate: true, deep: true }); return { data, loading, error }; }