From 4b0176079ef90c270603d89402215cf7d669cee8 Mon Sep 17 00:00:00 2001 From: Gubar Nikita Date: Fri, 29 Dec 2023 12:23:54 +0300 Subject: [PATCH] debug ModalRegistration and RegistrationForCandidate --- .envexample | 2 - src/components/AuthBox/AuthBox.jsx | 4 +- .../ModalRegistration/ModalRegistration.jsx | 203 ++++++------------ src/hooks/useFormValidation.js | 47 ++-- .../RegistrationForCandidate.js | 69 +++--- 5 files changed, 128 insertions(+), 197 deletions(-) delete mode 100644 .envexample diff --git a/.envexample b/.envexample deleted file mode 100644 index 1acf8a19..00000000 --- a/.envexample +++ /dev/null @@ -1,2 +0,0 @@ -REACT_APP_API_URL = https://dev.itguild.info/api -REACT_APP_BASE_URL = https://dev.itguild.info/api \ No newline at end of file diff --git a/src/components/AuthBox/AuthBox.jsx b/src/components/AuthBox/AuthBox.jsx index 1f37549e..4751a4ae 100644 --- a/src/components/AuthBox/AuthBox.jsx +++ b/src/components/AuthBox/AuthBox.jsx @@ -87,12 +87,12 @@ export const AuthBox = ({ title }) => { )}
- +
{ - const [inputsValue, setInputsValue] = useState({ - userName: "", + const [loader, setLoader] = useState(false); + + const fields = { + username: "", email: "", password: "", secondPassword: "" - }); - - const [inputsError, setInputsError] = useState({ - name: false, - email: false, - password: false, - secondPassword: false - }); - - const [loader, setLoader] = useState(false); - - const validateEmail = (email) => { - // регулярное выражение для проверки email - const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - - // возвращаем true, если email проходит проверку, и false, если нет - return re.test(email); }; + const closeModal = () => { + setActive(false); + handleClearForm(); + }; + + const apiEndpoint = "/register/sign-up"; const { showNotification } = useNotification(); - - const validateForm = () => { - if (inputsValue.password.length < 6) { - setInputsError((prevValue) => ({ ...prevValue, password: true })); - } - if (inputsValue.password !== inputsValue.secondPassword) { - setInputsError((prevValue) => ({ ...prevValue, secondPassword: true })); - } - if (inputsValue.userName.length < 2) { - setInputsError((prevValue) => ({ ...prevValue, name: true })); - } - if (!validateEmail(inputsValue.email)) { - setInputsError((prevValue) => ({ ...prevValue, email: true })); - } - if ( - inputsValue.password.length < 6 || - inputsValue.userName.length < 6 || - !validateEmail(inputsValue.email) - ) { - return true; - } + const showNotificationError = () => { + showNotification({ + show: true, + text: "Аккаунт с таким логином или email уже существует", + type: "error" + }); }; - - const submitHandler = () => { - if (validateForm()) { - return; - } - setLoader(true); - apiRequest("/register/sign-up", { - method: "POST", - data: { - username: inputsValue.userName, - email: inputsValue.email, - password: inputsValue.password - } - }).then((data) => { - setLoader(false); - if (!data) { - showNotification({ - show: true, - text: "Аккаунт с таким логином или email уже существует", - type: "error" - }); - } else { - closeModal(); - showNotification({ - show: true, - text: "Аккаунт успешно создан", - type: "success" - }); - } + const showNotificationTrue = () => { + showNotification({ + show: true, + text: "Аккаунт успешно создан", + type: "success" }); }; - const closeModal = () => { - setInputsValue({ - userName: "", - email: "", - password: "" - }); - setInputsError({ - name: false, - email: false, - password: false - }); - setActive(false); - }; + const { + formData, + validationErrors, + handleChange, + handleSubmit, + handleClearForm + } = useFormValidation( + apiEndpoint, + fields, + showNotificationError, + showNotificationTrue, + closeModal + ); + return (
@@ -122,43 +74,25 @@ export const ModalRegistration = ({ active, setActive }) => {
Ваше имя
{ - setInputsError({ - name: false, - email: false, - password: false - }); - setInputsValue((prevValue) => ({ - ...prevValue, - userName: e.target.value - })); - }} - value={inputsValue.userName} + className={validationErrors.username ? "error" : ""} + onChange={handleChange} + value={formData.username} placeholder="Имя" + id="username" /> - {inputsError.name && Минимум 2 символа} + {validationErrors.username}
E-mail
{ - setInputsError({ - name: false, - email: false, - password: false - }); - setInputsValue((prevValue) => ({ - ...prevValue, - email: e.target.value - })); - }} - value={inputsValue.email} + className={validationErrors.email ? "error" : ""} + onChange={handleChange} + value={formData.email} placeholder="Почта" + id="email" /> - {inputsError.email && Введите корректный e-mail} + {validationErrors.email}
@@ -166,46 +100,26 @@ export const ModalRegistration = ({ active, setActive }) => {
Пароль
{ - setInputsError({ - name: false, - email: false, - password: false - }); - setInputsValue((prevValue) => ({ - ...prevValue, - password: e.target.value - })); - }} - value={inputsValue.password} + onChange={handleChange} + value={formData.password} placeholder="Пароль" + id="password" /> - {inputsError.password && Минимум 6 символов} + {validationErrors.password}
Повторите пароль
{ - setInputsError({ - name: false, - email: false, - secondPassword: false - }); - setInputsValue((prevValue) => ({ - ...prevValue, - secondPassword: e.target.value - })); - }} - value={inputsValue.secondPassword} + onChange={handleChange} + value={formData.secondPassword} placeholder="Пароль" + id="secondPassword" /> - {inputsError.secondPassword && ( - Пароли должны совпадать - )} + {validationErrors.secondPassword}
@@ -217,7 +131,10 @@ export const ModalRegistration = ({ active, setActive }) => { { e.preventDefault(); - submitHandler(); + setLoader(true); + handleSubmit(e); + setLoader(false); + closeModal(); }} styles="button-box__submit" > diff --git a/src/hooks/useFormValidation.js b/src/hooks/useFormValidation.js index 192e7d83..40ac4f31 100644 --- a/src/hooks/useFormValidation.js +++ b/src/hooks/useFormValidation.js @@ -23,9 +23,9 @@ export const useFormValidation = ( // Функция для валидации формы const validateForm = () => { const errors = {}; - if (formData.name != undefined) { - if (formData.name.trim() === "") { - errors.name = "Имя обязательно к заполнению"; + if (formData.username != undefined) { + if (formData.username.trim() === "") { + errors.username = "Имя обязательно к заполнению"; } } @@ -66,23 +66,39 @@ export const useFormValidation = ( return Object.keys(errors).length === 0; }; + // Функция отчистки формы + const handleClearForm = () => { + const clearedFormData = Object.fromEntries( + Object.keys(formData).map((key) => [key, ""]) + ); + setFormData(clearedFormData); + + const clearedValidationErrors = Object.fromEntries( + Object.keys(validationErrors).map((key) => [key, ""]) + ); + setValidationErrors(clearedValidationErrors); + }; + // Функция для обработки отправки формы const handleSubmit = async (e) => { e.preventDefault(); - // Проверка валидации формы if (validateForm()) { - try { - const response = await apiRequest(apiEndpoint, { - method: "POST", - data: formData - }); + let newformData = { ...formData }; + delete newformData.secondPassword; - if (!response) { - showNotificationError(); - } else { - showNotificationTrue(); - } + try { + apiRequest(apiEndpoint, { + method: "POST", + data: newformData + }).then((data) => { + if ("errors" in data) { + showNotificationError(); + } else { + handleClearForm(); + showNotificationTrue(); + } + }); } catch (error) { console.error("Error submitting form:", error); } @@ -93,6 +109,7 @@ export const useFormValidation = ( formData, validationErrors, handleChange, - handleSubmit + handleSubmit, + handleClearForm }; }; diff --git a/src/pages/RegistrationForCandidate/RegistrationForCandidate.js b/src/pages/RegistrationForCandidate/RegistrationForCandidate.js index e883b877..e0f9b40b 100644 --- a/src/pages/RegistrationForCandidate/RegistrationForCandidate.js +++ b/src/pages/RegistrationForCandidate/RegistrationForCandidate.js @@ -17,7 +17,7 @@ export const RegistrationForCandidate = () => { const apiEndpoint = "/register/sign-up"; const fields = { - name: "", + username: "", summary: "", email: "", tg: "", @@ -41,12 +41,13 @@ export const RegistrationForCandidate = () => { }); }; - const form = useFormValidation( - apiEndpoint, - fields, - showNotificationError, - showNotificationTrue - ); + const { formData, validationErrors, handleChange, handleSubmit } = + useFormValidation( + apiEndpoint, + fields, + showNotificationError, + showNotificationTrue + ); return (
@@ -79,81 +80,79 @@ export const RegistrationForCandidate = () => { {/* форма регистрации */}
- {form.validationErrors.name} + {validationErrors.username}
- {form.validationErrors.summary} + {validationErrors.summary}
- {form.validationErrors.email} + {validationErrors.email}
- {form.validationErrors.tg} + {validationErrors.tg}
- {form.validationErrors.password} + {validationErrors.password}
- {form.validationErrors.secondPassword} + {validationErrors.secondPassword}