23 lines
737 B
TypeScript
23 lines
737 B
TypeScript
"use client";
|
|
|
|
import { useTransition } from "react";
|
|
import { toast } from "sonner";
|
|
import type { ActionResult } from "@/lib/action-result";
|
|
|
|
export function useAction<Args extends unknown[], T>(action: (...args: Args) => Promise<ActionResult<T>>, options?: { successMessage?: string; onSuccess?: (data: T) => void }) {
|
|
const [isPending, startTransition] = useTransition();
|
|
|
|
function run(...args: Args) {
|
|
startTransition(async () => {
|
|
const result = await action(...args);
|
|
if (result.success) {
|
|
if (options?.successMessage) toast.success(options.successMessage);
|
|
options?.onSuccess?.(result.data);
|
|
} else {
|
|
toast.error(result.error);
|
|
}
|
|
});
|
|
}
|
|
|
|
return { run, isPending };
|
|
} |