turash/bugulma/frontend/hooks/useFormState.ts
Damir Mukimov 6347f42e20
Consolidate repositories: Remove nested frontend .git and merge into main repository
- Remove nested git repository from bugulma/frontend/.git
- Add all frontend files to main repository tracking
- Convert from separate frontend/backend repos to unified monorepo
- Preserve all frontend code and development history as tracked files
- Eliminate nested repository complexity for simpler development workflow

This creates a proper monorepo structure with frontend and backend
coexisting in the same repository for easier development and deployment.
2025-11-25 06:02:57 +01:00

73 lines
1.7 KiB
TypeScript

import { useCallback, useState } from 'react';
/**
* Hook for managing common form state patterns
*/
export function useFormState<T>(
initialData: T,
options: {
onSubmit?: (data: T) => Promise<void> | void;
onSuccess?: () => void;
onError?: (error: Error) => void;
validate?: (data: T) => string | null;
} = {}
) {
const [data, setData] = useState<T>(initialData);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isDirty, setIsDirty] = useState(false);
const updateData = useCallback((updates: Partial<T>) => {
setData(prev => ({ ...prev, ...updates }));
setIsDirty(true);
setError(null);
}, []);
const reset = useCallback(() => {
setData(initialData);
setError(null);
setIsDirty(false);
}, [initialData]);
const validate = useCallback(() => {
if (options.validate) {
const validationError = options.validate(data);
if (validationError) {
setError(validationError);
return false;
}
}
return true;
}, [data, options]);
const submit = useCallback(async () => {
if (!validate()) return;
setIsSubmitting(true);
setError(null);
try {
await options.onSubmit?.(data);
options.onSuccess?.();
setIsDirty(false);
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
setError(error.message);
options.onError?.(error);
} finally {
setIsSubmitting(false);
}
}, [data, validate, options]);
return {
data,
updateData,
reset,
submit,
isSubmitting,
error,
isDirty,
isValid: !error && validate(),
};
}