47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from "react";
|
|
|
|
interface AsyncState<T> {
|
|
data: T | null;
|
|
loading: boolean;
|
|
error: string | null;
|
|
reload: () => void;
|
|
}
|
|
|
|
/** Runs an async factory on mount (and on reload), tracking loading/error so
|
|
* every API-backed surface has a complete state. Best-effort, no `any`. */
|
|
export function useAsyncData<T>(fn: () => Promise<T>, deps: readonly unknown[] = []): AsyncState<T> {
|
|
const [data, setData] = useState<T | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const fnRef = useRef(fn);
|
|
fnRef.current = fn;
|
|
const depsKey = deps.join("\u0000");
|
|
|
|
const run = useCallback(() => {
|
|
let cancelled = false;
|
|
setLoading(true);
|
|
setError(null);
|
|
fnRef
|
|
.current()
|
|
.then((res) => {
|
|
if (!cancelled) setData(res);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setError(err instanceof Error ? err.message : "加载失败");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [depsKey]);
|
|
|
|
useEffect(() => {
|
|
const cancel = run();
|
|
return cancel;
|
|
}, [run]);
|
|
|
|
return { data, loading, error, reload: run };
|
|
}
|