forked from CyCraft/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.ts
100 lines (87 loc) · 2.22 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
88
89
90
91
92
93
94
95
96
97
98
99
100
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: unknown) => void
/**
* Sets the state to initialState before executing the promise.
*
* This can be useful when calling the execute function more than once (for
* example, to refresh data). When set to false, the current state remains
* unchanged until the promise resolves.
*
* @default true
*/
resetOnExecute?: boolean
}
/**
* 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> | ((...args: any[]) => Promise<T>),
initialState: T,
options: AsyncStateOptions = {},
) {
const {
immediate = true,
delay = 0,
onError = noop,
resetOnExecute = true,
} = options
const state = shallowRef(initialState)
const isReady = ref(false)
const error = ref<unknown | undefined>(undefined)
async function execute(delay = 0, ...args: any[]) {
if (resetOnExecute)
state.value = initialState
error.value = undefined
isReady.value = false
if (delay > 0)
await promiseTimeout(delay)
const _promise = typeof promise === 'function'
? promise(...args)
: 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,
error,
execute,
}
}
export type UseAsyncStateReturn = ReturnType<typeof useAsyncState>