diff --git a/ts/graphs/async.ts b/ts/graphs/async.ts index 073ba42a9..e03185dbf 100644 --- a/ts/graphs/async.ts +++ b/ts/graphs/async.ts @@ -1,14 +1,14 @@ import { Readable, readable, derived } from "svelte/store"; -interface AsyncData { +export interface AsyncData { value: Readable, error: Readable, pending: Readable, - successful: Readable, + success: Readable, } -function useAsync(asyncFunction: () => Promise): AsyncData { +function useAsync(asyncFunction: () => Promise): AsyncData { const promise = asyncFunction(); const value = readable(null, (set: (value: T) => void) => { @@ -19,10 +19,10 @@ function useAsync(asyncFunction: () => Promise): AsyncData set(value)) }) - const pending = derived([value, error], (_, set) => set(true), true) - const successful = derived([value], (_, set) => set(true), false) + const pending = derived([value, error], (_, set) => set(false), true) + const success= derived([value], (_, set) => set(true), false) - return { value, error, pending, successful } + return { value, error, pending, success } } export default useAsync diff --git a/ts/graphs/asyncRefresh.ts b/ts/graphs/asyncRefresh.ts new file mode 100644 index 000000000..3d813cbab --- /dev/null +++ b/ts/graphs/asyncRefresh.ts @@ -0,0 +1,30 @@ +import { Readable, derived, get } from "svelte/store"; +import useAsync, { AsyncData } from "./async"; + +interface AsyncRefreshData { + value: Readable, + error: Readable, + pending: Readable, + success: Readable, + loading: Readable, +} + + +function useAsyncRefresh(asyncFunction: () => Promise, dependencies: [Readable, ...Readable[]]): AsyncRefreshData { + const current = derived( + dependencies, + (_, set: (value: AsyncData) => void) => set(useAsync(asyncFunction)), + useAsync(asyncFunction), + ) + + const value = derived(current, ($current, set: (value: T | null) => void) => set(get($current.value)), null) + const error = derived(current, ($current, set: (error: E | null) => void) => set(get($current.error)), null) + + const pending = derived(current, (_, set) => set(false), true) + const success = derived(current, ($current, set: (success: boolean) => void) => set(get($current.success)), false) + const loading = derived(current, ($current, set: (pending: boolean) => void) => set(get($current.pending)), true) + + return { value, error, pending, success, loading } +} + +export default useAsyncRefresh