From f82a02bd2e35ffdb1833d20469f58a1afcb4d72a Mon Sep 17 00:00:00 2001 From: Henrik Giesel Date: Sun, 21 Mar 2021 19:43:59 +0100 Subject: [PATCH] Add Svelte async hook --- ts/graphs/async.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 ts/graphs/async.ts diff --git a/ts/graphs/async.ts b/ts/graphs/async.ts new file mode 100644 index 000000000..073ba42a9 --- /dev/null +++ b/ts/graphs/async.ts @@ -0,0 +1,28 @@ +import { Readable, readable, derived } from "svelte/store"; + +interface AsyncData { + value: Readable, + error: Readable, + pending: Readable, + successful: Readable, +} + + +function useAsync(asyncFunction: () => Promise): AsyncData { + 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 pending = derived([value, error], (_, set) => set(true), true) + const successful = derived([value], (_, set) => set(true), false) + + return { value, error, pending, successful } +} + +export default useAsync