Skip to content

Commit

Permalink
feat(useAsyncState): add onSuccess callbacks (#2562)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alfred-Skyblue committed Dec 23, 2022
1 parent bb0fd59 commit ed64fce
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions packages/core/useAsyncState/index.ts
Expand Up @@ -10,7 +10,7 @@ export interface UseAsyncStateReturn<Data, Shallow extends boolean> {
execute: (delay?: number, ...args: any[]) => Promise<Data>
}

export interface UseAsyncStateOptions<Shallow extends boolean> {
export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {
/**
* Delay for executing the promise. In milliseconds.
*
Expand All @@ -33,6 +33,12 @@ export interface UseAsyncStateOptions<Shallow extends boolean> {
*/
onError?: (e: unknown) => void

/**
* Callback when success is caught.
* @param {D} data
*/
onSuccess?: (data: D) => void

/**
* Sets the state to initialState before executing the promise.
*
Expand Down Expand Up @@ -71,17 +77,17 @@ export interface UseAsyncStateOptions<Shallow extends boolean> {
export function useAsyncState<Data, Shallow extends boolean = true>(
promise: Promise<Data> | ((...args: any[]) => Promise<Data>),
initialState: Data,
options?: UseAsyncStateOptions<Shallow>,
options?: UseAsyncStateOptions<Shallow, Data>,
): UseAsyncStateReturn<Data, Shallow> {
const {
immediate = true,
delay = 0,
onError = noop,
onSuccess = noop,
resetOnExecute = true,
shallow = true,
throwError,
} = options ?? {}

const state = shallow ? shallowRef(initialState) : ref(initialState)
const isReady = ref(false)
const isLoading = ref(false)
Expand All @@ -105,6 +111,7 @@ export function useAsyncState<Data, Shallow extends boolean = true>(
const data = await _promise
state.value = data
isReady.value = true
onSuccess(data)
}
catch (e) {
error.value = e
Expand Down

0 comments on commit ed64fce

Please sign in to comment.