-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0d41d1a
commit c8625fb
Showing
2 changed files
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
export * from "./use-origin"; | ||
export * from "./use-scroll-top"; | ||
export * from "./use-sidebar-layout"; | ||
export * from "./use-transition"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
"use client"; | ||
|
||
import { useCallback, useState } from "react"; | ||
|
||
type Action<T> = (() => T) | (() => Promise<T>); | ||
|
||
export const useTransition = <T>(fn: Action<T>) => { | ||
const [isPending, setIsPending] = useState(false); | ||
const [error, setError] = useState<Error>(); | ||
|
||
const action = useCallback(async () => { | ||
try { | ||
setIsPending(true); | ||
const response = fn(); | ||
if (response instanceof Promise) return await response; | ||
return response; | ||
} catch (error) { | ||
setError(error as Error); | ||
} finally { | ||
setIsPending(false); | ||
} | ||
}, [fn]); | ||
|
||
return [action, isPending, error] as const; | ||
}; |