Add (probably non-working) asyncRefresh

This commit is contained in:
Henrik Giesel 2021-03-21 20:16:40 +01:00
parent f82a02bd2e
commit a9c16a3cd8
2 changed files with 36 additions and 6 deletions

View file

@ -1,14 +1,14 @@
import { Readable, readable, derived } from "svelte/store";
interface AsyncData<T, E> {
export interface AsyncData<T, E> {
value: Readable<T | null>,
error: Readable<E | null>,
pending: Readable<boolean>,
successful: Readable<boolean>,
success: Readable<boolean>,
}
function useAsync<T, E = Error>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
function useAsync<T, E = unknown>(asyncFunction: () => Promise<T>): AsyncData<T, E> {
const promise = asyncFunction();
const value = readable(null, (set: (value: T) => void) => {
@ -19,10 +19,10 @@ function useAsync<T, E = Error>(asyncFunction: () => Promise<T>): AsyncData<T, E
promise.catch((value: E) => 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

30
ts/graphs/asyncRefresh.ts Normal file
View file

@ -0,0 +1,30 @@
import { Readable, derived, get } from "svelte/store";
import useAsync, { AsyncData } from "./async";
interface AsyncRefreshData<T, E> {
value: Readable<T | null>,
error: Readable<E | null>,
pending: Readable<boolean>,
success: Readable<boolean>,
loading: Readable<boolean>,
}
function useAsyncRefresh<T, E = unknown>(asyncFunction: () => Promise<T>, dependencies: [Readable<unknown>, ...Readable<unknown>[]]): AsyncRefreshData<T, E> {
const current = derived(
dependencies,
(_, set: (value: AsyncData<T, E>) => void) => set(useAsync<T, E>(asyncFunction)),
useAsync<T, E>(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