kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
44 lines (43 loc) • 1.56 kB
JavaScript
import { useState, useCallback } from 'react';
import { ZodError } from 'zod';
export function useForm(schema, initialState) {
const [formData, setFormData] = useState(initialState);
const [errors, setErrors] = useState({});
const handleChange = useCallback((e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
if (errors[name]) {
setErrors(prev => {
const newErrors = { ...prev };
delete newErrors[name];
return newErrors;
});
}
}, [errors]);
const handleSubmit = (onSubmit) => {
return async (e) => {
e.preventDefault();
setErrors({});
try {
const validatedData = schema.parse(formData);
await onSubmit(validatedData);
}
catch (error) {
if (error instanceof ZodError) {
const formattedErrors = {};
error.errors.forEach(err => {
const fieldName = err.path[0];
if (!formattedErrors[fieldName]) {
formattedErrors[fieldName] = err.message;
}
});
setErrors(formattedErrors);
}
else {
console.error("An unexpected error occurred:", error);
}
}
};
};
return { formData, errors, handleChange, handleSubmit };
}