-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
87 lines (76 loc) · 1.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { noop, promiseTimeout } from '@vueuse/shared'
import { ref, shallowRef } from 'vue-demi'
export interface AsyncStateOptions {
/**
* Delay for executing the promise. In milliseconds.
*
* @default 0
*/
delay?: number
/**
* Excute the promise right after the function is invoked.
* Will apply the delay if any.
*
* When set to false, you will need to execute it manually.
*
* @default true
*/
immediate?: boolean
/**
* Callback when error is caught.
*/
onError?: (e: Error) => void
}
/**
* Reactive async state. Will not block your setup function and will triggers changes once
* the promise is ready.
*
* @see https://vueuse.org/useAsyncState
* @param promise The promise / async function to be resolved
* @param initialState The initial state, used until the first evaluation finishes
* @param options
*/
export function useAsyncState<T>(
promise: Promise<T> | (() => Promise<T>),
initialState: T,
options: AsyncStateOptions = {},
) {
const {
immediate = true,
delay = 0,
onError = noop,
} = options
const state = shallowRef(initialState)
const isReady = ref(false)
const error = ref<Error | undefined>(undefined)
async function execute(delay = 0) {
state.value = initialState
error.value = undefined
isReady.value = false
if (!delay)
await promiseTimeout(delay)
const _promise = typeof promise === 'function'
? promise()
: promise
try {
const data = await _promise
// @ts-ignore
state.value = data
isReady.value = true
}
catch (e) {
error.value = e
onError(e)
}
}
if (immediate)
execute(delay)
return {
state,
isReady,
/** @deprecated, use isReady instead */
ready: isReady,
error,
execute,
}
}