Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useAsyncState): add onSuccess callbacks #2562

Merged
merged 3 commits into from Dec 23, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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