Добавил редюсеры

This commit is contained in:
gg12 darfren 2023-12-15 19:53:17 +04:00
parent 3b8c199a38
commit a0b391de56
15 changed files with 276 additions and 102 deletions

View File

@ -7,50 +7,56 @@
"id": 1 "id": 1
}, },
{ {
"handle": "vk1d", "handle": "vk1d2004",
"email": "vk1d@mail.ru", "email": "vk1d@mail.ru",
"password": "1234", "password": "1234",
"id": 3 "id": 2
},
{
"email": "av@gmail.com",
"handle": "bor",
"password": "123",
"id": 4
} }
], ],
"groups": [ "groups": [
{ {
"name": "asd", "name": "group",
"memberCount": "2", "memberCount": "2",
"userId": 3, "userId": 1,
"id": 1 "id": 3
}, },
{ {
"name": "wefhhce9 ", "name": "vk1dgroup",
"memberCount": "-1", "memberCount": "2",
"userId": 4, "userId": 2,
"id": 2 "id": 4
} }
], ],
"members": [ "members": [
{ {
"name": "dsa", "name": "oleg",
"handle": "-", "handle": "-",
"groupId": 1, "groupId": 3,
"id": 1 "id": 4
}, },
{ {
"name": "casd", "name": "vasya",
"handle": "-", "handle": "-",
"groupId": 1, "groupId": 3,
"id": 2 "id": 5
}, },
{ {
"name": "nigers", "name": "tonya",
"handle": "-", "handle": "-",
"groupId": 2, "groupId": 3,
"id": 3 "id": 6
},
{
"name": "lexa",
"handle": "-",
"groupId": 4,
"id": 7
},
{
"name": "niga",
"handle": "-",
"groupId": 4,
"id": 8
} }
] ]
} }

View File

@ -1,13 +1,11 @@
import './ExitComponent.css'; import './ExitComponent.css';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { useContext } from 'react'; import useUser from '../../../../providers/hooks/UserHook.jsx';
import { UserContext } from '../../../../providers/UserProvider.jsx';
const ExitComponent = () => { const ExitComponent = () => {
const { setUser } = useContext(UserContext); const { userLogout } = useUser();
const makeExit = () => { const makeExit = () => {
setUser(null); userLogout();
localStorage.removeItem('user');
}; };
return ( return (
<Link to = '/' onClick = {makeExit}> <Link to = '/' onClick = {makeExit}>

View File

@ -2,16 +2,16 @@ import { useContext } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { AddGroupContext } from '../../providers/AddGroupProvider.jsx';
import AddGroupApiService from './service/AddGroupApiService/AddGroupApiService.jsx'; import AddGroupApiService from './service/AddGroupApiService/AddGroupApiService.jsx';
import { UserContext } from '../../providers/UserProvider.jsx'; import { UserContext } from '../../providers/UserProvider.jsx';
import { CurrentGroupContext } from '../../providers/CurrentGroupProvider.jsx'; import useGroup from '../../providers/hooks/CurrentGroupHook.jsx';
import useSteps from '../../providers/hooks/AddGroupHook.jsx';
const AddGroupPage = () => { const AddGroupPage = () => {
const { setSteps } = useContext(AddGroupContext); const { stepsChange } = useSteps();
const { user } = useContext(UserContext); const { user } = useContext(UserContext);
console.log(user); console.log(user);
const { setGroup } = useContext(CurrentGroupContext); const { groupChange } = useGroup();
const { register, handleSubmit, formState: { errors } } = useForm(); const { register, handleSubmit, formState: { errors } } = useForm();
console.log(errors); console.log(errors);
const navigate = useNavigate(); const navigate = useNavigate();
@ -25,13 +25,7 @@ const AddGroupPage = () => {
userId: user.id, userId: user.id,
}; };
}; };
return ( const makeSubmit = async (data) => {
<main>
<div className="container-fluid">
<div className="row">
<div className="add-group">
<div className="form-group col-7">
<form className = "form-horizontal" onSubmit = {handleSubmit(async (data) => {
if (isNumeric(data.memberCount) !== true) { if (isNumeric(data.memberCount) !== true) {
alert('кол-во участников должно быть числом'); alert('кол-во участников должно быть числом');
return; return;
@ -39,12 +33,19 @@ const AddGroupPage = () => {
// eslint-disable-next-line radix // eslint-disable-next-line radix
const val = Number.parseInt(data.memberCount); const val = Number.parseInt(data.memberCount);
console.log(val); console.log(val);
setSteps(val); stepsChange(val);
localStorage.setItem('steps', val);
const curGroup = await AddGroupApiService.create(getNewGroup(data)); const curGroup = await AddGroupApiService.create(getNewGroup(data));
setGroup(curGroup); groupChange(curGroup);
await localStorage.setItem('group', JSON.stringify(curGroup));
navigate('/addmember'); navigate('/addmember');
};
return (
<main>
<div className="container-fluid">
<div className="row">
<div className="add-group">
<div className="form-group col-7">
<form className = "form-horizontal" onSubmit = {handleSubmit(async (data) => {
await makeSubmit(data);
})}> })}>
<label>название</label> <label>название</label>
<input {...register('name', { required: 'Это поле обязательно' })} className="form-control " type="handle" placeholder="название"></input> <input {...register('name', { required: 'Это поле обязательно' })} className="form-control " type="handle" placeholder="название"></input>

View File

@ -5,10 +5,11 @@ import { useForm } from 'react-hook-form';
import { AddGroupContext } from '../../providers/AddGroupProvider.jsx'; import { AddGroupContext } from '../../providers/AddGroupProvider.jsx';
import AddMemberApiService from './service/AddMemberApiService/AddMemberApiService.jsx'; import AddMemberApiService from './service/AddMemberApiService/AddMemberApiService.jsx';
import { CurrentGroupContext } from '../../providers/CurrentGroupProvider.jsx'; import { CurrentGroupContext } from '../../providers/CurrentGroupProvider.jsx';
import useSteps from '../../providers/hooks/AddGroupHook.jsx';
const AddMember = () => { const AddMember = () => {
const { steps, setSteps } = useContext(AddGroupContext); const { steps } = useContext(AddGroupContext);
localStorage.setItem('steps', steps); const { stepsChange } = useSteps();
const { group } = useContext(CurrentGroupContext); const { group } = useContext(CurrentGroupContext);
const { const {
register, reset, handleSubmit, formState: { errors }, register, reset, handleSubmit, formState: { errors },
@ -27,16 +28,10 @@ const AddMember = () => {
groupId: group.id, groupId: group.id,
}; };
}; };
return ( const onSubmit = async (data) => {
<main> await AddMemberApiService.create(getNewMember(data));
<div className="container-fluid">
<div className="row">
<div className="add-group">
<div className="form-group col-7">
<form className = 'form-horizontal' onSubmit = {handleSubmit(async (data) => {
AddMemberApiService.create(getNewMember(data));
const cursteps = steps - 1; const cursteps = steps - 1;
setSteps(cursteps); stepsChange(cursteps);
if (cursteps !== 0) { if (cursteps !== 0) {
console.log(steps); console.log(steps);
navigate('/addmember'); navigate('/addmember');
@ -45,6 +40,15 @@ const AddMember = () => {
navigate('/'); navigate('/');
} }
reset(); reset();
};
return (
<main>
<div className="container-fluid">
<div className="row">
<div className="add-group">
<div className="form-group col-7">
<form className = 'form-horizontal' onSubmit = {handleSubmit(async (data) => {
await onSubmit(data);
})}> })}>
<label>имя участника </label> <label>имя участника </label>
<input {...register('name', { required: 'Это поле обязательно' })} className="form-control " type="handle" placeholder="имя участника"></input> <input {...register('name', { required: 'Это поле обязательно' })} className="form-control " type="handle" placeholder="имя участника"></input>

View File

@ -2,23 +2,15 @@ import './login.css';
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useContext } from 'react';
import LoginApiService from '../service/loginapiservice'; import LoginApiService from '../service/loginapiservice';
import { UserContext } from '../../../../providers/UserProvider.jsx'; import useUser from '../../../../providers/hooks/UserHook.jsx';
const Login = () => { const Login = () => {
const { setUser } = useContext(UserContext); const { userLogin } = useUser();
const { register, handleSubmit, formState: { errors } } = useForm(); const { register, handleSubmit, formState: { errors } } = useForm();
console.log(errors); console.log(errors);
const navigate = useNavigate(); const navigate = useNavigate();
return ( const makeSubmit = async (data) => {
<main className="d-flex align-items-center">
<div className="register-panel container-fluid p-0 m-0 ">
<div className="container-fluid d-flex align-items-center">
<div className="col-md-4 offset-md-4 col-12">
<div className="form-container mt-auto">
<form className="form-horizontal" onSubmit = {handleSubmit(async (data) => {
const res1 = await LoginApiService.getByHandle(data.handle); const res1 = await LoginApiService.getByHandle(data.handle);
if (res1.length === 0) { if (res1.length === 0) {
alert('Пользователся с таким хэндлом не существует'); alert('Пользователся с таким хэндлом не существует');
@ -28,9 +20,18 @@ const Login = () => {
alert('Введен неверный пароль'); alert('Введен неверный пароль');
return; return;
} }
setUser(res1[0]); userLogin(res1[0]);
localStorage.setItem('user', JSON.stringify(res1[0]));
navigate('/'); navigate('/');
};
return (
<main className="d-flex align-items-center">
<div className="register-panel container-fluid p-0 m-0 ">
<div className="container-fluid d-flex align-items-center">
<div className="col-md-4 offset-md-4 col-12">
<div className="form-container mt-auto">
<form className="form-horizontal" onSubmit = {handleSubmit(async (data) => {
await makeSubmit(data);
})}> })}>
<div className="form-group"> <div className="form-group">
<label>хэндл</label> <label>хэндл</label>

View File

@ -2,15 +2,14 @@ import './reg.css';
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
import { useForm } from 'react-hook-form'; import { useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { useContext } from 'react';
import RegApiService from '../service/regapiservice'; import RegApiService from '../service/regapiservice';
import { UserContext } from '../../../../providers/UserProvider.jsx'; import useUser from '../../../../providers/hooks/UserHook.jsx';
const Reg = () => { const Reg = () => {
const { register, handleSubmit, formState: { errors } } = useForm(); const { register, handleSubmit, formState: { errors } } = useForm();
console.log(errors); console.log(errors);
const navigate = useNavigate(); const navigate = useNavigate();
const { setUser } = useContext(UserContext); const { userLogin } = useUser();
const getNewUser = (formData) => { const getNewUser = (formData) => {
const emailt = formData.email; const emailt = formData.email;
const handlet = formData.handle; const handlet = formData.handle;
@ -21,14 +20,7 @@ const Reg = () => {
password: passwordt, password: passwordt,
}; };
}; };
return ( const makeSubmit = async (data) => {
<main className = "d-flex align-items-center">
<div className="register-panel container-fluid ">
<div className="container-fluid d-flex align-items-center">
<div className="col-md-4 offset-md-4 col-12">
<div className="form-container">
<form className="form-horizontal" onSubmit = {handleSubmit(async (data) => {
console.log(data); console.log(data);
const res1 = await RegApiService.getByHandle(data.handle); const res1 = await RegApiService.getByHandle(data.handle);
if (res1.length !== 0) { if (res1.length !== 0) {
@ -42,9 +34,18 @@ const Reg = () => {
} }
const newUser = getNewUser(data); const newUser = getNewUser(data);
const curUser = await RegApiService.create(newUser); const curUser = await RegApiService.create(newUser);
setUser(curUser); userLogin(curUser);
localStorage.setItem('user', JSON.stringify(curUser));
navigate('/registersuccess'); navigate('/registersuccess');
};
return (
<main className = "d-flex align-items-center">
<div className="register-panel container-fluid ">
<div className="container-fluid d-flex align-items-center">
<div className="col-md-4 offset-md-4 col-12">
<div className="form-container">
<form className="form-horizontal" onSubmit = {handleSubmit(async (data) => {
await makeSubmit(data);
})}> })}>
<div className="form-group"> <div className="form-group">
<label>хэндл</label> <label>хэндл</label>

View File

@ -1,12 +1,17 @@
import { createContext, useState } from 'react'; import { createContext, useReducer, useEffect } from 'react';
import { loadSteps, saveSteps, stepsReducer } from './reducers/AddGroupReducer.jsx';
export const AddGroupContext = createContext(null); export const AddGroupContext = createContext(null);
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
export const AddGroupProvider = ({ children }) => { export const AddGroupProvider = ({ children }) => {
const [steps, setSteps] = useState(localStorage.getItem('steps') || 0); const [steps, dispatch] = useReducer(stepsReducer, null, loadSteps);
return <AddGroupContext.Provider value = {{ steps, setSteps }}> useEffect(() => {
saveSteps(steps || null);
}, [steps]);
return <AddGroupContext.Provider value = {{ steps, dispatch }}>
{children} {children}
</AddGroupContext.Provider>; </AddGroupContext.Provider>;
}; };

View File

@ -1,12 +1,17 @@
import { createContext, useState } from 'react'; import { createContext, useReducer, useEffect } from 'react';
import { groupReducer, loadGroup, saveGroup } from './reducers/CurrentGroupReducer.jsx';
export const CurrentGroupContext = createContext(null); export const CurrentGroupContext = createContext(null);
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
export const CurrentGroupProvider = ({ children }) => { export const CurrentGroupProvider = ({ children }) => {
const [group, setGroup] = useState(JSON.parse(localStorage.getItem('group')) || null); const [group, dispatch] = useReducer(groupReducer, null, loadGroup);
return <CurrentGroupContext.Provider value = {{ group, setGroup }}> useEffect(() => {
saveGroup(group || null);
}, [group]);
return <CurrentGroupContext.Provider value = {{ group, dispatch }}>
{children} {children}
</CurrentGroupContext.Provider>; </CurrentGroupContext.Provider>;
}; };

View File

@ -1,11 +1,17 @@
import { createContext, useState } from 'react'; import { createContext, useReducer, useEffect } from 'react';
import { loadUser, saveUser, userReducer } from './reducers/UserReduser.jsx';
export const UserContext = createContext(null); export const UserContext = createContext(null);
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
export const UserProvider = ({ children }) => { export const UserProvider = ({ children }) => {
const [user, setUser] = useState(JSON.parse(localStorage.getItem('user')) || null); const [user, dispatch] = useReducer(userReducer, null, loadUser);
return <UserContext.Provider value = {{ user, setUser }}>
useEffect(() => {
saveUser(user || null);
}, [user]);
return <UserContext.Provider value = {{ user, dispatch }}>
{children} {children}
</UserContext.Provider>; </UserContext.Provider>;
}; };

View File

@ -0,0 +1,13 @@
import { useContext } from 'react';
import { AddGroupContext } from '../AddGroupProvider.jsx';
import { stepsChange } from '../reducers/AddGroupReducer.jsx';
const useSteps = () => {
const { dispatch } = useContext(AddGroupContext);
return {
stepsChange: (steps) => dispatch(stepsChange(steps)),
};
};
export default useSteps;

View File

@ -0,0 +1,13 @@
import { useContext } from 'react';
import { CurrentGroupContext } from '../CurrentGroupProvider.jsx';
import { groupChange } from '../reducers/CurrentGroupReducer.jsx';
const useGroup = () => {
const { dispatch } = useContext(CurrentGroupContext);
return {
groupChange: (group) => dispatch(groupChange(group)),
};
};
export default useGroup;

View File

@ -0,0 +1,14 @@
import { useContext } from 'react';
import { UserContext } from '../UserProvider.jsx';
import { userLogout, userLogin } from '../reducers/UserReduser.jsx';
const useUser = () => {
const { dispatch } = useContext(UserContext);
return {
userLogout: () => dispatch(userLogout()),
userLogin: (user) => dispatch(userLogin(user)),
};
};
export default useUser;

View File

@ -0,0 +1,34 @@
const STEPS_KEY = 'steps';
const STEPS_CHANGE = 'steps/change';
export const saveSteps = (steps) => {
localStorage.setItem('steps', JSON.stringify(steps));
};
export const loadSteps = (initialValue = []) => {
const stepsData = localStorage.getItem(STEPS_KEY);
if (stepsData) {
return JSON.parse(stepsData);
}
return initialValue;
};
export const stepsReducer = (prevSteps, action) => {
console.log(action);
const { steps } = action;
switch (action.type) {
case STEPS_CHANGE: {
return steps;
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const stepsChange = (steps) => {
console.log(steps);
return ({
type: STEPS_CHANGE, steps,
});
};

View File

@ -0,0 +1,34 @@
const GROUP_KEY = 'group';
const GROUP_CHANGE = 'group/change';
export const saveGroup = (group) => {
localStorage.setItem('group', JSON.stringify(group));
};
export const loadGroup = (initialValue = []) => {
const groupData = localStorage.getItem(GROUP_KEY);
if (groupData) {
return JSON.parse(groupData);
}
return initialValue;
};
export const groupReducer = (prevGroup, action) => {
const { group } = action;
console.log(group);
switch (action.type) {
case GROUP_CHANGE: {
return group;
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const groupChange = (group) => {
console.log(group);
return ({
type: GROUP_CHANGE, group,
});
};

View File

@ -0,0 +1,39 @@
const USER_KEY = 'user';
const USER_LOGIN = 'user/login';
const USER_LOGOUT = 'user/logout';
export const saveUser = (user) => {
localStorage.setItem('user', JSON.stringify(user));
};
export const loadUser = (initialValue = []) => {
const userData = localStorage.getItem(USER_KEY);
if (userData) {
return JSON.parse(userData);
}
return initialValue;
};
export const userReducer = (prevUser, action) => {
console.log(action);
const { user } = action;
switch (action.type) {
case USER_LOGOUT: {
return null;
}
case USER_LOGIN: {
return user;
}
default: {
throw Error(`Unknown action: ${action.type}`);
}
}
};
export const userLogout = () => ({
type: USER_LOGOUT,
});
export const userLogin = (user) => ({
type: USER_LOGIN, user,
});