From ed64fce636ceff2b225156ddffa550c0f18938f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=B6=E8=BF=9C=E6=96=B9?= Date: Sat, 24 Dec 2022 03:38:52 +0800 Subject: [PATCH] feat(useAsyncState): add onSuccess callbacks (#2562) --- packages/core/useAsyncState/index.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/core/useAsyncState/index.ts b/packages/core/useAsyncState/index.ts index d8cb1dfc6d0..6a7c978612e 100644 --- a/packages/core/useAsyncState/index.ts +++ b/packages/core/useAsyncState/index.ts @@ -10,7 +10,7 @@ export interface UseAsyncStateReturn { execute: (delay?: number, ...args: any[]) => Promise } -export interface UseAsyncStateOptions { +export interface UseAsyncStateOptions { /** * Delay for executing the promise. In milliseconds. * @@ -33,6 +33,12 @@ export interface UseAsyncStateOptions { */ 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. * @@ -71,17 +77,17 @@ export interface UseAsyncStateOptions { export function useAsyncState( promise: Promise | ((...args: any[]) => Promise), initialState: Data, - options?: UseAsyncStateOptions, + options?: UseAsyncStateOptions, ): UseAsyncStateReturn { 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) @@ -105,6 +111,7 @@ export function useAsyncState( const data = await _promise state.value = data isReady.value = true + onSuccess(data) } catch (e) { error.value = e