46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useState } from "react";
|
|
|
|
import { HubError } from "./api";
|
|
|
|
export interface AsyncValue<T> {
|
|
data?: T;
|
|
error?: string;
|
|
loading: boolean;
|
|
reload: () => void;
|
|
}
|
|
|
|
/** Minimal fetch-on-mount hook; `deps` usually carries a socket revision. */
|
|
export function useAsync<T>(loader: () => Promise<T>, deps: unknown[]): AsyncValue<T> {
|
|
const [data, setData] = useState<T>();
|
|
const [error, setError] = useState<string>();
|
|
const [loading, setLoading] = useState(true);
|
|
const [nonce, setNonce] = useState(0);
|
|
const reload = useCallback(() => setNonce((value) => value + 1), []);
|
|
|
|
useEffect(() => {
|
|
let ignore = false;
|
|
setLoading(true);
|
|
loader()
|
|
.then((value) => {
|
|
if (ignore) return;
|
|
setData(value);
|
|
setError(undefined);
|
|
})
|
|
.catch((exc: unknown) => {
|
|
if (ignore) return;
|
|
setError(exc instanceof HubError ? exc.message : String(exc));
|
|
})
|
|
.finally(() => {
|
|
if (!ignore) setLoading(false);
|
|
});
|
|
return () => {
|
|
ignore = true;
|
|
};
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [...deps, nonce]);
|
|
|
|
return { data, error, loading, reload };
|
|
}
|