Skip to content

Commit

Permalink
feat: react add use async call func
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr.Mao committed Jun 4, 2024
1 parent c2cbf04 commit a107328
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/react-utils/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './useEventBus'
export * from './useMounted'
export * from './useWatch'
export * from './useWhenever'
export * from './useAsyncCallback'
21 changes: 21 additions & 0 deletions packages/react-utils/src/hooks/useAsyncCallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useState } from 'react'

export function useAsyncCallback<T extends (...args: any[]) => any>(fun: T) {
const [error, setError] = useState<Error>()
const [loading, setLoading] = useState(false)
async function execute(...args: any[]) {
try {
setLoading(true)
const result = await fun(...args)
setLoading(false)
return result
}
catch (error: any) {
setLoading(false)
setError(error)
throw error
}
}

return [loading, execute as unknown as T, error] as const
}

0 comments on commit a107328

Please sign in to comment.