Skip to content

Commit

Permalink
tmp: useTransition
Browse files Browse the repository at this point in the history
  • Loading branch information
steeeee0223 committed Dec 27, 2024
1 parent 0d41d1a commit c8625fb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/ui/src/hooks/index.ts
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";
25 changes: 25 additions & 0 deletions packages/ui/src/hooks/use-transition.ts
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;
};

0 comments on commit c8625fb

Please sign in to comment.