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