anki/ts/sveltelib/async.ts
Henrik Giesel 10b8a1c3cb Move async and asyncReactive to sveltelib
- sveltelib is a lib for component-agnostic svelte utils
2021-03-22 03:06:53 +01:00

31 lines
853 B
TypeScript

import { Readable, readable, derived } from "svelte/store";
interface AsyncData<T, E> {
value: Readable<T | null>;
error: Readable<E | null>;
loading: Readable<boolean>;
success: Readable<boolean>;
}
function useAsync<T, E = unknown>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
const promise = asyncFunction();
const value = readable(null, (set: (value: T) => void) => {
promise.then((value: T) => set(value));
});
const error = readable(null, (set: (value: E) => void) => {
promise.catch((value: E) => set(value));
});
const loading = readable(true, (set: (value: boolean) => void) => {
promise.finally(() => set(false));
});
const success = derived([value], (_, set) => set(true), false);
return { value, error, loading, success };
}
export default useAsync;