Files
bakery-ia/frontend/src/components/domain/unified-wizard/shared/useWizardSubmit.ts

62 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-11-16 22:13:52 +01:00
/**
* useWizardSubmit - Standardized hook for wizard submission
*
* Provides consistent loading states, error handling, and success callbacks
* across all wizard types.
*/
import { useState, useCallback } from 'react';
interface UseWizardSubmitOptions<T> {
onSubmit: (data: T) => Promise<void>;
onSuccess?: (data: T) => void;
onError?: (error: Error) => void;
}
interface UseWizardSubmitReturn<T> {
submit: (data: T) => Promise<void>;
loading: boolean;
error: string | null;
clearError: () => void;
}
export function useWizardSubmit<T>({
onSubmit,
onSuccess,
onError,
}: UseWizardSubmitOptions<T>): UseWizardSubmitReturn<T> {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const submit = useCallback(
async (data: T) => {
setLoading(true);
setError(null);
try {
await onSubmit(data);
onSuccess?.(data);
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'An error occurred during submission';
setError(errorMessage);
onError?.(err instanceof Error ? err : new Error(errorMessage));
} finally {
setLoading(false);
}
},
[onSubmit, onSuccess, onError]
);
const clearError = useCallback(() => {
setError(null);
}, []);
return {
submit,
loading,
error,
clearError,
};
}