anki/ts/sveltelib/asyncReactive.ts

50 lines
1.2 KiB
TypeScript
Raw Normal View History

import { Readable, derived } from "svelte/store";
2021-03-21 21:38:23 +01:00
interface AsyncReativeData<T, E> {
2021-03-21 21:07:35 +01:00
value: Readable<T | null>;
error: Readable<E | null>;
loading: Readable<boolean>;
}
2021-03-21 21:38:23 +01:00
function useAsyncReactive<T, E>(
2021-03-21 21:07:35 +01:00
asyncFunction: () => Promise<T>,
dependencies: [Readable<unknown>, ...Readable<unknown>[]]
2021-03-21 21:38:23 +01:00
): AsyncReativeData<T, E> {
const promise = derived(
dependencies,
(_, set: (value: Promise<T> | null) => void) => set(asyncFunction()),
// initialize with null to avoid duplicate fetch on init
null
);
2021-03-21 21:07:35 +01:00
const value = derived(
promise,
($promise, set: (value: T) => void) => {
$promise?.then((value: T) => set(value));
2021-03-21 21:07:35 +01:00
},
null
);
2021-03-21 21:07:35 +01:00
const error = derived(
promise,
($promise, set: (error: E | null) => void) => {
$promise?.catch((error: E) => set(error));
2021-03-21 22:06:25 +01:00
return () => set(null);
2021-03-21 21:07:35 +01:00
},
null
);
2021-03-21 21:07:35 +01:00
const loading = derived(
promise,
($promise, set: (value: boolean) => void) => {
$promise?.finally(() => set(false));
2021-03-21 21:07:35 +01:00
return () => set(true);
},
true
);
return { value, error, loading };
}
2021-03-21 21:38:23 +01:00
export default useAsyncReactive;