MCPcopy Create free account
hub / github.com/cn-docs/vueuse / useAsyncState

Function useAsyncState

packages/core/useAsyncState/index.ts:81–158  ·  view source on GitHub ↗
(
  promise: Promise<Data> | ((...args: Params) => Promise<Data>),
  initialState: Data,
  options?: UseAsyncStateOptions<Shallow, Data>,
)

Source from the content-addressed store, hash-verified

79 * @param options
80 */
81export function useAsyncState<Data, Params extends any[] = any[], Shallow extends boolean = true>(
82 promise: Promise<Data> | ((...args: Params) => Promise<Data>),
83 initialState: Data,
84 options?: UseAsyncStateOptions<Shallow, Data>,
85): UseAsyncStateReturn<Data, Params, Shallow> {
86 const {
87 immediate = true,
88 delay = 0,
89 onError = noop,
90 onSuccess = noop,
91 resetOnExecute = true,
92 shallow = true,
93 throwError,
94 } = options ?? {}
95 const state = shallow ? shallowRef(initialState) : deepRef(initialState)
96 const isReady = shallowRef(false)
97 const isLoading = shallowRef(false)
98 const error = shallowRef<unknown | undefined>(undefined)
99
100 async function execute(delay = 0, ...args: any[]) {
101 if (resetOnExecute)
102 state.value = initialState
103 error.value = undefined
104 isReady.value = false
105 isLoading.value = true
106
107 if (delay > 0)
108 await promiseTimeout(delay)
109
110 const _promise = typeof promise === 'function'
111 ? promise(...args as Params)
112 : promise
113
114 try {
115 const data = await _promise
116 state.value = data
117 isReady.value = true
118 onSuccess(data)
119 }
120 catch (e) {
121 error.value = e
122 onError(e)
123 if (throwError)
124 throw e
125 }
126 finally {
127 isLoading.value = false
128 }
129
130 return state.value as Data
131 }
132
133 if (immediate) {
134 execute(delay)
135 }
136
137 const shell: UseAsyncStateReturnBase<Data, Params, Shallow> = {
138 state: state as Shallow extends true ? ShallowRef<Data> : Ref<UnwrapRef<Data>>,

Callers 2

index.test.tsFile · 0.90
useImageFunction · 0.90

Calls 1

executeFunction · 0.70

Tested by

no test coverage detected