requests for auth/register
This commit is contained in:
parent
9a3f05ef60
commit
bc293f6370
9 changed files with 348 additions and 63 deletions
|
|
@ -6,14 +6,14 @@ import SettingSurvey from "./components/SettingSurvey/SettingSurvey.tsx";
|
||||||
import {MySurveysPage} from "./pages/MySurveysPage/MySurveysPage.tsx";
|
import {MySurveysPage} from "./pages/MySurveysPage/MySurveysPage.tsx";
|
||||||
import {Results} from "./components/Results/Results.tsx";
|
import {Results} from "./components/Results/Results.tsx";
|
||||||
import {MySurveyList} from "./components/MySurveyList/MySurveyList.tsx";
|
import {MySurveyList} from "./components/MySurveyList/MySurveyList.tsx";
|
||||||
import LoginForm from "./components/LoginForm/LoginForm.tsx";
|
|
||||||
import AuthForm from "./pages/AuthForm/AuthForm.tsx";
|
import AuthForm from "./pages/AuthForm/AuthForm.tsx";
|
||||||
|
|
||||||
const App = () => {
|
const App = () => {
|
||||||
return(
|
return(
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<LoginForm />} />
|
<Route path="/login" element={<AuthForm />} />
|
||||||
|
<Route path="/register" element={<AuthForm />} />
|
||||||
|
|
||||||
<Route path="survey/create" element={<SurveyCreateAndEditingPage />}>
|
<Route path="survey/create" element={<SurveyCreateAndEditingPage />}>
|
||||||
<Route path="questions" element={<Survey />} />
|
<Route path="questions" element={<Survey />} />
|
||||||
|
|
@ -31,8 +31,6 @@ const App = () => {
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
<Route path="*" element={<AuthForm />} />
|
<Route path="*" element={<AuthForm />} />
|
||||||
<Route path="/login" element={<AuthForm />} />
|
|
||||||
<Route path="/register" element={<AuthForm />} />
|
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,13 @@ export const registerUser = async (data: IRegistrationData) => {
|
||||||
const response = await fetch(`${BASE_URL}/auth/register`, {
|
const response = await fetch(`${BASE_URL}/auth/register`, {
|
||||||
...createRequestConfig('POST'), body: JSON.stringify(data),
|
...createRequestConfig('POST'), body: JSON.stringify(data),
|
||||||
})
|
})
|
||||||
return await handleResponse(response);
|
const responseData = await handleResponse(response);
|
||||||
|
|
||||||
|
if (responseData.accessToken) {
|
||||||
|
localStorage.setItem("token", responseData.accessToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
} catch (error){
|
} catch (error){
|
||||||
console.error("Registration error:", error);
|
console.error("Registration error:", error);
|
||||||
throw error;
|
throw error;
|
||||||
|
|
@ -24,14 +30,22 @@ export const registerUser = async (data: IRegistrationData) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
export const authUser = async (data: IAuthData) => {
|
export const authUser = async (data: IAuthData) => {
|
||||||
try{
|
try {
|
||||||
const response = await fetch(`${BASE_URL}/auth/login`, {
|
const response = await fetch(`${BASE_URL}/auth/login`, {
|
||||||
...createRequestConfig('POST'), body: JSON.stringify(data),
|
...createRequestConfig('POST'),
|
||||||
})
|
body: JSON.stringify(data),
|
||||||
return await handleResponse(response);
|
});
|
||||||
}
|
const responseData = await handleResponse(response);
|
||||||
catch(error){
|
console.log("Полный ответ сервера:", responseData); // Добавьте эту строку
|
||||||
|
|
||||||
|
const token = responseData.accessToken || responseData.token;
|
||||||
|
if (token) {
|
||||||
|
localStorage.setItem("token", token);
|
||||||
|
}
|
||||||
|
|
||||||
|
return responseData;
|
||||||
|
} catch (error) {
|
||||||
console.error("Login error:", error);
|
console.error("Login error:", error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
@ -13,7 +13,8 @@ interface RequestConfig {
|
||||||
* @returns Конфигурация для fetch-запроса
|
* @returns Конфигурация для fetch-запроса
|
||||||
*/
|
*/
|
||||||
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
|
const createRequestConfig = (method: string, isFormData: boolean = false): RequestConfig => {
|
||||||
const token = localStorage.getItem("accessToken");
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
const config: RequestConfig = {
|
const config: RequestConfig = {
|
||||||
method,
|
method,
|
||||||
headers: {},
|
headers: {},
|
||||||
|
|
@ -37,14 +38,36 @@ const createRequestConfig = (method: string, isFormData: boolean = false): Reque
|
||||||
* @param response Ответ от fetch
|
* @param response Ответ от fetch
|
||||||
* @returns Распарсенные данные или ошибку
|
* @returns Распарсенные данные или ошибку
|
||||||
*/
|
*/
|
||||||
const handleResponse = async (response: Response) => {
|
// const handleResponse = async (response: Response) => {
|
||||||
const data = await response.json();
|
// const data = await response.json();
|
||||||
|
//
|
||||||
|
// if (!response.ok) {
|
||||||
|
// throw new Error(data.message || "Произошла ошибка");
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// return data;
|
||||||
|
// };
|
||||||
|
|
||||||
if (!response.ok) {
|
const handleResponse = async (response: Response) => {
|
||||||
throw new Error(data.message || "Произошла ошибка");
|
// Проверяем, есть ли контент в ответе
|
||||||
|
const responseText = await response.text();
|
||||||
|
|
||||||
|
if (!responseText) {
|
||||||
|
if (response.ok) {
|
||||||
|
return null; // Если ответ пустой, но статус 200, возвращаем null
|
||||||
|
}
|
||||||
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data;
|
try {
|
||||||
|
const data = JSON.parse(responseText);
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.message || `HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Не удалось разобрать ответ сервера: ${e}`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export { BASE_URL, createRequestConfig, handleResponse };
|
export { BASE_URL, createRequestConfig, handleResponse };
|
||||||
29
SurveyFrontend/src/api/QuestionApi.ts
Normal file
29
SurveyFrontend/src/api/QuestionApi.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts";
|
||||||
|
|
||||||
|
export interface INewQuestion{
|
||||||
|
title: string;
|
||||||
|
questionType: string;
|
||||||
|
answerVariants: string[];
|
||||||
|
}
|
||||||
|
//
|
||||||
|
// export interface IErrorQuestionResponse {
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
|
||||||
|
export const addNewQuestion = async (surveyId: number, question: INewQuestion) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}/questions`, {
|
||||||
|
...createRequestConfig('POST'),
|
||||||
|
body: JSON.stringify(question),
|
||||||
|
})
|
||||||
|
return await handleResponse(response)
|
||||||
|
} catch (error){
|
||||||
|
throw new Error(`Error when adding a new question: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
117
SurveyFrontend/src/api/SurveyApi.ts
Normal file
117
SurveyFrontend/src/api/SurveyApi.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
||||||
|
import {BASE_URL, createRequestConfig, handleResponse} from "./BaseApi.ts";
|
||||||
|
|
||||||
|
export interface ISurvey {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
createdBy: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface INewSurvey{
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* getMySurveys - запрос на получение моих опросов
|
||||||
|
*/
|
||||||
|
export const getMySurveys = async (): Promise<ISurvey[]> => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/my`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
});
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error receiving surveys:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* getAllSurvey - запрос на получение всех опросов
|
||||||
|
*/
|
||||||
|
export const getAllSurveys = async (): Promise<ISurvey[]> => {
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
})
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error receiving surveys:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* postNewSurvey - добавление нового опроса
|
||||||
|
* @param survey
|
||||||
|
*/
|
||||||
|
export const postNewSurvey = async (survey: INewSurvey): Promise<INewSurvey> => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys`, {
|
||||||
|
...createRequestConfig('POST'),
|
||||||
|
body: JSON.stringify(survey)
|
||||||
|
})
|
||||||
|
|
||||||
|
// return await handleResponse(response);
|
||||||
|
|
||||||
|
if (response.status === 201) {
|
||||||
|
return await handleResponse(response);
|
||||||
|
}
|
||||||
|
throw new Error(`Ожидался код 201, получен ${response.status}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error when adding a new survey: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запрос на получение опроса по заданному ID
|
||||||
|
* @param surveyId - ID опроса
|
||||||
|
*/
|
||||||
|
export const getSurveyById = async (surveyId: number): Promise<ISurvey> => {
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}`, {
|
||||||
|
...createRequestConfig('GET'),
|
||||||
|
})
|
||||||
|
return await handleResponse(response);
|
||||||
|
} catch (error){
|
||||||
|
console.error(`Error finding the survey by id: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Запрос на удаление опроса
|
||||||
|
* @param surveyId - ID выбранного опроса
|
||||||
|
*/
|
||||||
|
export const deleteSurvey = async (surveyId: string) => {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
if (!token) {
|
||||||
|
throw new Error("Токен отсутствует");
|
||||||
|
}
|
||||||
|
|
||||||
|
try{
|
||||||
|
const response = await fetch(`${BASE_URL}/surveys/${surveyId}`, {
|
||||||
|
...createRequestConfig('DELETE'),
|
||||||
|
})
|
||||||
|
const responseData = await handleResponse(response);
|
||||||
|
if (response.ok && !responseData){
|
||||||
|
return {success: true};
|
||||||
|
}
|
||||||
|
return responseData;
|
||||||
|
} catch (error){
|
||||||
|
console.error(`Error deleting a survey: ${error}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,20 +1,45 @@
|
||||||
import { Link } from "react-router-dom";
|
import {Link, useNavigate} from "react-router-dom";
|
||||||
import styles from './LoginForm.module.css';
|
import styles from './LoginForm.module.css';
|
||||||
import { useState } from 'react';
|
import {useRef, useState} from 'react';
|
||||||
|
import {authUser} from "../../api/AuthApi.ts";
|
||||||
|
|
||||||
const RegisterForm = () => {
|
const LoginForm = () => {
|
||||||
const [focused, setFocused] = useState({
|
const [focused, setFocused] = useState({
|
||||||
email: false,
|
email: false,
|
||||||
password: false
|
password: false
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const emailRef = useRef<HTMLInputElement>(null); // ref для поля email
|
||||||
|
const passwordRef = useRef<HTMLInputElement>(null); // ref для поля password
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const email = emailRef.current?.value || '';
|
||||||
|
const password = passwordRef.current?.value || '';
|
||||||
|
|
||||||
|
try{
|
||||||
|
const responseData = await authUser({email, password});
|
||||||
|
if (responseData && !responseData.error)
|
||||||
|
navigate('/my-surveys');
|
||||||
|
else
|
||||||
|
console.error('Ошибка аутентификации:', responseData);
|
||||||
|
}
|
||||||
|
catch(err){
|
||||||
|
console.error('Ошибка при отправке запроса:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.loginContainer}>
|
<div className={styles.loginContainer}>
|
||||||
<h2 className={styles.title}>С возвращением!</h2>
|
<h2 className={styles.title}>С возвращением!</h2>
|
||||||
<form className={styles.form}>
|
<form className={styles.form} onSubmit={handleSubmit}>
|
||||||
<input
|
<input
|
||||||
className={`${styles.input} ${styles.email}`}
|
className={`${styles.input} ${styles.email}`}
|
||||||
type={'email'}
|
type={'email'}
|
||||||
placeholder='Почта'
|
placeholder='Почта'
|
||||||
|
ref={emailRef}
|
||||||
onFocus={() => setFocused({ ...focused, email: true })}
|
onFocus={() => setFocused({ ...focused, email: true })}
|
||||||
onBlur={() => setFocused({ ...focused, email: false })}
|
onBlur={() => setFocused({ ...focused, email: false })}
|
||||||
style={{ color: focused.email ? 'black' : 'inherit' }}
|
style={{ color: focused.email ? 'black' : 'inherit' }}
|
||||||
|
|
@ -23,11 +48,12 @@ const RegisterForm = () => {
|
||||||
className={`${styles.input} ${styles.password}`}
|
className={`${styles.input} ${styles.password}`}
|
||||||
type='password'
|
type='password'
|
||||||
placeholder='Пароль'
|
placeholder='Пароль'
|
||||||
|
ref={passwordRef}
|
||||||
onFocus={() => setFocused({ ...focused, password: true })}
|
onFocus={() => setFocused({ ...focused, password: true })}
|
||||||
onBlur={() => setFocused({ ...focused, password: false })}
|
onBlur={() => setFocused({ ...focused, password: false })}
|
||||||
style={{ color: focused.password ? 'black' : 'inherit' }}
|
style={{ color: focused.password ? 'black' : 'inherit' }}
|
||||||
/>
|
/>
|
||||||
<button className={styles.signIn}>Войти</button>
|
<button className={styles.signIn} type="submit">Войти</button>
|
||||||
</form>
|
</form>
|
||||||
<p className={styles.recommendation}>Еще не с нами?
|
<p className={styles.recommendation}>Еще не с нами?
|
||||||
<Link className={styles.recommendationLink} to='/register'>Зарегистрируйтесь!</Link>
|
<Link className={styles.recommendationLink} to='/register'>Зарегистрируйтесь!</Link>
|
||||||
|
|
@ -36,4 +62,4 @@ const RegisterForm = () => {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default RegisterForm;
|
export default LoginForm;
|
||||||
|
|
|
||||||
|
|
@ -1,35 +1,58 @@
|
||||||
import styles from './MySurveysList.module.css'
|
import styles from './MySurveysList.module.css'
|
||||||
import {useNavigate} from "react-router-dom";
|
import {useNavigate} from "react-router-dom";
|
||||||
|
import {useEffect, useState} from "react";
|
||||||
|
import {getMySurveys, ISurvey} from "../../api/SurveyApi.ts";
|
||||||
|
|
||||||
interface MySurveyItem{
|
|
||||||
id: string,
|
interface MySurveyItem extends ISurvey{
|
||||||
title: string,
|
|
||||||
description: string,
|
|
||||||
date: string
|
|
||||||
status: 'active' | 'completed'
|
status: 'active' | 'completed'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const MySurveyList = () => {
|
export const MySurveyList = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [surveys, setSurveys] = useState<MySurveyItem[]>([]);
|
||||||
|
|
||||||
const surveys: MySurveyItem[] = [
|
useEffect(() => {
|
||||||
{
|
const fetchSurvey = async () => {
|
||||||
id: '1',
|
try {
|
||||||
title: 'Опрос 1',
|
const mySurveys = await getMySurveys();
|
||||||
description: 'Описание опроса 1',
|
const surveysWithStatus: MySurveyItem[] = mySurveys.map((survey: ISurvey) => ({
|
||||||
date: '27-04-2025',
|
...survey,
|
||||||
status: 'active',
|
status: 'active',
|
||||||
},
|
}));
|
||||||
{
|
setSurveys(surveysWithStatus);
|
||||||
id: '2',
|
} catch (error) {
|
||||||
title: 'Опрос 2',
|
console.error('Ошибка при получении списка опросов:', error);
|
||||||
description: 'Описание опроса 2',
|
|
||||||
date: '01-01-2025',
|
|
||||||
status: 'completed',
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
const handleSurveyClick = (id: string) => {
|
if (error instanceof Error && error.message.includes("401")) {
|
||||||
|
// Если ошибка 401, перенаправляем на страницу входа
|
||||||
|
navigate('/login');
|
||||||
|
} else {
|
||||||
|
alert("Ошибка при загрузке опросов: " + (error instanceof Error && error.message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchSurvey();
|
||||||
|
}, [navigate]);
|
||||||
|
|
||||||
|
// const surveys: MySurveyItem[] = [
|
||||||
|
// {
|
||||||
|
// id: '1',
|
||||||
|
// title: 'Опрос 1',
|
||||||
|
// description: 'Описание опроса 1',
|
||||||
|
// createdBy: '27-04-2025',
|
||||||
|
// status: 'active',
|
||||||
|
// },
|
||||||
|
// {
|
||||||
|
// id: '2',
|
||||||
|
// title: 'Опрос 2',
|
||||||
|
// description: 'Описание опроса 2',
|
||||||
|
// createdBy: '01-01-2025',
|
||||||
|
// status: 'completed',
|
||||||
|
// }
|
||||||
|
// ]
|
||||||
|
|
||||||
|
const handleSurveyClick = (id: number) => {
|
||||||
navigate(`/survey/${id}/questions`)
|
navigate(`/survey/${id}/questions`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,7 +69,7 @@ export const MySurveyList = () => {
|
||||||
<h1 className={styles.title}>{survey.title}</h1>
|
<h1 className={styles.title}>{survey.title}</h1>
|
||||||
<h2 className={styles.description}>{survey.description}</h2>
|
<h2 className={styles.description}>{survey.description}</h2>
|
||||||
</div>
|
</div>
|
||||||
<span className={styles.date}>Дата создания: {survey.date}</span>
|
<span className={styles.date}>Дата создания: {survey.createdBy}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className={`${styles.status} ${
|
<div className={`${styles.status} ${
|
||||||
survey.status === 'active' ? styles.active : styles.completed
|
survey.status === 'active' ? styles.active : styles.completed
|
||||||
|
|
|
||||||
|
|
@ -1,38 +1,75 @@
|
||||||
import { Link } from "react-router-dom";
|
import {Link, useNavigate} from "react-router-dom";
|
||||||
import styles from './RegisterForm.module.css';
|
import styles from './RegisterForm.module.css';
|
||||||
import { useState } from 'react';
|
import {useRef, useState} from 'react';
|
||||||
|
import {registerUser} from "../../api/AuthApi.ts";
|
||||||
|
|
||||||
const RegisterForm = () => {
|
const RegisterForm = () => {
|
||||||
const [focused, setFocused] = useState({
|
const [focused, setFocused] = useState({
|
||||||
name: false,
|
firstName: false,
|
||||||
surname: false,
|
lastName: false,
|
||||||
email: false,
|
email: false,
|
||||||
password: false
|
password: false
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const nameRef = useRef<HTMLInputElement>(null);
|
||||||
|
const surnameRef = useRef<HTMLInputElement>(null);
|
||||||
|
const emailRef = useRef<HTMLInputElement>(null);
|
||||||
|
const passwordRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const firstName = nameRef.current?.value || '';
|
||||||
|
const lastName = surnameRef.current?.value || '';
|
||||||
|
const email = emailRef.current?.value || '';
|
||||||
|
const password = passwordRef.current?.value || '';
|
||||||
|
const username = firstName + lastName || '';
|
||||||
|
|
||||||
|
try{
|
||||||
|
const responseData = await registerUser({username, firstName, lastName, email, password});
|
||||||
|
console.log(responseData); //проверка вывода данных
|
||||||
|
if (responseData && !responseData.error) {
|
||||||
|
console.log('Регистрация успешна')
|
||||||
|
navigate('/my-surveys');
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.error(`Ошибка регистрации: ${responseData}`);
|
||||||
|
console.log('Регистраиця не удалась');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.error(`Ошибка при отправке запроса ${err}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.registerContainer}>
|
<div className={styles.registerContainer}>
|
||||||
<h2 className={styles.title}>Регистрация</h2>
|
<h2 className={styles.title}>Регистрация</h2>
|
||||||
<form className={styles.form}>
|
<form className={styles.form} onSubmit={handleSubmit}>
|
||||||
<input
|
<input
|
||||||
className={`${styles.input} ${styles.name}`}
|
className={`${styles.input} ${styles.name}`}
|
||||||
type={'text'}
|
type={'text'}
|
||||||
placeholder='Имя'
|
placeholder='Имя'
|
||||||
onFocus={() => setFocused({ ...focused, name: true })}
|
ref={nameRef}
|
||||||
onBlur={() => setFocused({ ...focused, name: false })}
|
onFocus={() => setFocused({ ...focused, firstName: true })}
|
||||||
style={{ color: focused.name ? 'black' : 'inherit' }}
|
onBlur={() => setFocused({ ...focused, firstName: false })}
|
||||||
|
style={{ color: focused.firstName ? 'black' : 'inherit' }}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
className={`${styles.input} ${styles.surname}`}
|
className={`${styles.input} ${styles.surname}`}
|
||||||
type={'text'}
|
type={'text'}
|
||||||
placeholder='Фамилия'
|
placeholder='Фамилия'
|
||||||
onFocus={() => setFocused({ ...focused, surname: true })}
|
ref={surnameRef}
|
||||||
onBlur={() => setFocused({ ...focused, surname: false })}
|
onFocus={() => setFocused({ ...focused, lastName: true })}
|
||||||
style={{ color: focused.surname ? 'black' : 'inherit' }}
|
onBlur={() => setFocused({ ...focused, lastName: false })}
|
||||||
|
style={{ color: focused.lastName ? 'black' : 'inherit' }}
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
className={`${styles.input} ${styles.email}`}
|
className={`${styles.input} ${styles.email}`}
|
||||||
type={'email'}
|
type={'email'}
|
||||||
placeholder='Почта'
|
placeholder='Почта'
|
||||||
|
ref={emailRef}
|
||||||
onFocus={() => setFocused({ ...focused, email: true })}
|
onFocus={() => setFocused({ ...focused, email: true })}
|
||||||
onBlur={() => setFocused({ ...focused, email: false })}
|
onBlur={() => setFocused({ ...focused, email: false })}
|
||||||
style={{ color: focused.email ? 'black' : 'inherit' }}
|
style={{ color: focused.email ? 'black' : 'inherit' }}
|
||||||
|
|
@ -41,11 +78,12 @@ const RegisterForm = () => {
|
||||||
className={`${styles.input} ${styles.password}`}
|
className={`${styles.input} ${styles.password}`}
|
||||||
type='password'
|
type='password'
|
||||||
placeholder='Пароль'
|
placeholder='Пароль'
|
||||||
|
ref={passwordRef}
|
||||||
onFocus={() => setFocused({ ...focused, password: true })}
|
onFocus={() => setFocused({ ...focused, password: true })}
|
||||||
onBlur={() => setFocused({ ...focused, password: false })}
|
onBlur={() => setFocused({ ...focused, password: false })}
|
||||||
style={{ color: focused.password ? 'black' : 'inherit' }}
|
style={{ color: focused.password ? 'black' : 'inherit' }}
|
||||||
/>
|
/>
|
||||||
<button className={styles.signUp}>Зарегистрироваться</button>
|
<button className={styles.signUp} type='submit'>Зарегистрироваться</button>
|
||||||
</form>
|
</form>
|
||||||
<p className={styles.recommendation}>Уже с нами?
|
<p className={styles.recommendation}>Уже с нами?
|
||||||
<Link className={styles.recommendationLink} to='/login'>Войдите!</Link>
|
<Link className={styles.recommendationLink} to='/login'>Войдите!</Link>
|
||||||
|
|
|
||||||
|
|
@ -5,13 +5,30 @@ import {useLocation} from "react-router-dom";
|
||||||
|
|
||||||
|
|
||||||
const AuthForm = () => {
|
const AuthForm = () => {
|
||||||
|
// const location = useLocation();
|
||||||
|
// const isLogin = location.pathname === '/login';
|
||||||
|
//
|
||||||
|
// return (
|
||||||
|
// <div className={`${isLogin ? styles.pageLogin : styles.page}`}>
|
||||||
|
// {isLogin ? <LoginForm /> : <RegisterForm/>}
|
||||||
|
// </div>
|
||||||
|
// );
|
||||||
|
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
const isLogin = location.pathname === '/login';
|
const isLoginPage = location.pathname === '/login';
|
||||||
|
const isRegisterPage = location.pathname === '/register';
|
||||||
|
|
||||||
|
let content;
|
||||||
|
if (isLoginPage) {
|
||||||
|
content = <LoginForm />;
|
||||||
|
} else if (isRegisterPage) {
|
||||||
|
content = <RegisterForm />;
|
||||||
|
} else {
|
||||||
|
content = <LoginForm />; // По умолчанию показываем LoginForm
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`${isLogin ? styles.pageLogin : styles.page}`}>
|
<div className={`${(isLoginPage || location.pathname === '/') ? styles.pageLogin : styles.page}`}>{content}</div>
|
||||||
{isLogin ? <LoginForm /> : <RegisterForm/>}
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue