35 lines
749 B
TypeScript
35 lines
749 B
TypeScript
import { Signal, useSignal } from "@preact/signals";
|
|
import { useEffect } from "preact/hooks";
|
|
|
|
export type QueryStatus<T> = {
|
|
type: "loading";
|
|
} | {
|
|
type: "complete";
|
|
data: T;
|
|
} | {
|
|
type: "error";
|
|
err: Error;
|
|
};
|
|
|
|
export function useAsync<T>(fn: () => Promise<T>): Signal<QueryStatus<T>> {
|
|
const state = useSignal({
|
|
type: "loading",
|
|
} as QueryStatus<T>);
|
|
useEffect(() => {
|
|
(async () => {
|
|
try {
|
|
const data = await fn();
|
|
state.value = {
|
|
type: "complete",
|
|
data: data,
|
|
};
|
|
} catch (err) {
|
|
state.value = {
|
|
type: "error",
|
|
err: err,
|
|
};
|
|
}
|
|
})();
|
|
}, []);
|
|
return state;
|
|
} |