Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

패키지 구조 변경 및 중복 로직 삭제 #796

Merged
merged 3 commits into from
Mar 15, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat: useForm hook 구현
LJW25 committed Mar 14, 2024
commit 80fe6178506be8a8cb9d18bdcee8b35e6929a066
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useCallback, useState } from 'react';

export const useForm = <T extends Record<string, any>>(
initialValues: T,
validate: (values: T) => Record<string, boolean>,
submitAction: (values: T, onSuccess?: () => void, onError?: () => void) => void,
{ onSuccess, onError }: { onSuccess?: () => void; onError?: () => void }
) => {
const [formValues, setFormValues] = useState<T>(initialValues);
const [errors, setErrors] = useState<Record<string, boolean>>({});

const updateInputValue = useCallback((key: string, value: any) => {
setFormValues((prev) => ({ ...prev, [key]: value }));
}, []);

const disableError = useCallback((errorKey: string) => {
setErrors((prev) => ({ ...prev, [errorKey]: false }));
}, []);

const validateForm = useCallback(() => {
const validationErrors = validate(formValues);
setErrors(validationErrors);
return Object.values(validationErrors).some((isError) => isError);
}, [formValues, validate]);

const handleSubmit = useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!validateForm()) {
submitAction(formValues, onSuccess, onError);
}
},
[formValues, onSuccess, onError, validateForm, submitAction]
);

return { formValues, errors, updateInputValue, disableError, handleSubmit };
};