Skip to content

Commit

Permalink
feat(useAsync): support onMutate, onCancel, onRefresh callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
vikiboss committed Aug 7, 2024
1 parent 94c1165 commit a129849
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/use-async-fn/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export interface UseAsyncFnOptions<T extends AnyFunc, D = Awaited<ReturnType<T>>
* a function to run when the value is mutated
*/
onMutate?: (value: D | undefined, params: Parameters<T> | []) => void
/**
* a function to run when the value is refreshed
*/
onRefresh?: (value: D | undefined, params: Parameters<T> | []) => void
}

export interface UseAsyncFnReturns<T extends AnyFunc, D = Awaited<ReturnType<T>>> {
Expand Down Expand Up @@ -123,6 +127,7 @@ export function useAsyncFn<T extends AnyFunc, D = Awaited<ReturnType<T>>>(
cancelOnUnmount = true,
onError,
onMutate,
onRefresh,
onCancel,
onBefore,
onSuccess,
Expand Down Expand Up @@ -155,6 +160,7 @@ export function useAsyncFn<T extends AnyFunc, D = Awaited<ReturnType<T>>>(
cancelOnUnmount,
onMutate,
onCancel,
onRefresh,
onError,
onBefore,
onSuccess,
Expand Down Expand Up @@ -211,8 +217,10 @@ export function useAsyncFn<T extends AnyFunc, D = Awaited<ReturnType<T>>>(
latest.current.onMutate?.(nextState, stateRef.current.params.value)
})

const refresh = useStableFn(() => {
return run(...stateRef.current.params.value)
const refresh = useStableFn(async () => {
const result = await run(...stateRef.current.params.value)
latest.current.onRefresh?.(result, stateRef.current.params.value)
return result
})

useMount(immediate && run)
Expand Down

0 comments on commit a129849

Please sign in to comment.