(
action: Action<TInput, TOutput>,
options: UseActionOptions<TOutput> = {},
)
| 15 | } |
| 16 | |
| 17 | export const useAction = <TInput, TOutput>( |
| 18 | action: Action<TInput, TOutput>, |
| 19 | options: UseActionOptions<TOutput> = {}, |
| 20 | ) => { |
| 21 | const [fieldErrors, setFieldErrors] = useState< |
| 22 | FieldErrors<TInput> | undefined |
| 23 | >(undefined); |
| 24 | const [error, setError] = useState<string | undefined>(undefined); |
| 25 | const [data, setData] = useState<TOutput | undefined>(undefined); |
| 26 | const [isLoading, setIsLoading] = useState<boolean>(false); |
| 27 | |
| 28 | const execute = useCallback( |
| 29 | async (input: TInput) => { |
| 30 | setIsLoading(true); |
| 31 | |
| 32 | try { |
| 33 | const result = await action(input); |
| 34 | |
| 35 | if (!result) { |
| 36 | return; |
| 37 | } |
| 38 | |
| 39 | setFieldErrors(result.fieldErrors); |
| 40 | |
| 41 | if (result.error) { |
| 42 | setError(result.error); |
| 43 | options.onError?.(result.error); |
| 44 | } |
| 45 | |
| 46 | if (result.data) { |
| 47 | setData(result.data); |
| 48 | options.onSuccess?.(result.data); |
| 49 | } |
| 50 | } finally { |
| 51 | setIsLoading(false); |
| 52 | options.onComplete?.(); |
| 53 | } |
| 54 | }, |
| 55 | [action, options], |
| 56 | ); |
| 57 | |
| 58 | return { |
| 59 | execute, |
| 60 | fieldErrors, |
| 61 | error, |
| 62 | data, |
| 63 | isLoading, |
| 64 | setFieldErrors, |
| 65 | }; |
| 66 | }; |
no outgoing calls
no test coverage detected