2021-04-13 10:57:08 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
2021-03-22 15:23:48 +01:00
|
|
|
import { Readable, readable } from "svelte/store";
|
2021-03-21 19:43:59 +01:00
|
|
|
|
2021-03-21 21:38:23 +01:00
|
|
|
interface AsyncData<T, E> {
|
2021-03-21 21:07:35 +01:00
|
|
|
value: Readable<T | null>;
|
|
|
|
error: Readable<E | null>;
|
2021-03-22 00:40:19 +01:00
|
|
|
loading: Readable<boolean>;
|
2021-03-21 19:43:59 +01:00
|
|
|
}
|
|
|
|
|
2021-03-21 20:16:40 +01:00
|
|
|
function useAsync<T, E = unknown>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
|
2021-03-21 19:43:59 +01:00
|
|
|
const promise = asyncFunction();
|
|
|
|
|
|
|
|
const value = readable(null, (set: (value: T) => void) => {
|
2021-03-21 21:07:35 +01:00
|
|
|
promise.then((value: T) => set(value));
|
|
|
|
});
|
2021-03-21 19:43:59 +01:00
|
|
|
|
|
|
|
const error = readable(null, (set: (value: E) => void) => {
|
2021-03-21 21:07:35 +01:00
|
|
|
promise.catch((value: E) => set(value));
|
|
|
|
});
|
|
|
|
|
2021-03-22 00:40:19 +01:00
|
|
|
const loading = readable(true, (set: (value: boolean) => void) => {
|
2021-03-21 21:07:35 +01:00
|
|
|
promise.finally(() => set(false));
|
|
|
|
});
|
2021-03-21 19:43:59 +01:00
|
|
|
|
2021-03-22 15:23:48 +01:00
|
|
|
return { value, error, loading };
|
2021-03-21 19:43:59 +01:00
|
|
|
}
|
|
|
|
|
2021-03-21 21:07:35 +01:00
|
|
|
export default useAsync;
|