import { useState, useCallback } from 'react'; import { ActionState, FieldErrors } from '@/lib/create-safe-action'; type Action = ( data: TInput ) => Promise>; interface UseActionOptions { onSuccess?: (data: TOutput) => void; onError?: (error: string) => void; onComplete?: () => void; } export const useAction = ( action: Action, options: UseActionOptions = {} ) => { const [fieldErrors, setFieldErrors] = useState< FieldErrors | undefined >(undefined); const [error, setError] = useState(undefined); const [data, setData] = useState(undefined); const [isLoading, setIsLoading] = useState(false); const execute = useCallback( async (input: TInput) => { setIsLoading(true); try { const result = await action(input); if (!result) return; setFieldErrors(result.fieldErrors); if (result.error) { setError(result.error); options.onError?.(result.error); } if (result.data) { setData(result.data); options.onSuccess?.(result.data); } } finally { setIsLoading(false); options.onComplete?.(); } }, [action, options] ); return { execute, fieldErrors, error, data, isLoading, }; };