authorization.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import React, {useState} from 'react';
  2. import {Link} from 'react-router-dom';
  3. import { actionAuthLogin } from '../store/authReducer';
  4. import { store } from '../store/store';
  5. import { connect } from 'react-redux';
  6. import {history} from '../App';
  7. export async function SendForm (url, data) {
  8. let error = await fetch(`http://player-api/api/${url}`, {
  9. method: 'POST',
  10. body: data
  11. }).then(res => res.json())
  12. .then((data) => {
  13. if(data.token) {
  14. history.push('/user');
  15. store.dispatch(actionAuthLogin(data.token, data.user));
  16. return data
  17. } else {
  18. return data.message;
  19. }
  20. })
  21. console.log(error)
  22. return error;
  23. }
  24. export const LoginForm = ({authState}) => {
  25. const [login, setLogin] = useState('');
  26. const [password, setPassword] = useState('');
  27. const [textModal, setTextModal] = useState('');
  28. const postForm = async(event) =>{
  29. event.preventDefault();
  30. const data = new FormData();
  31. data.append("login", login);
  32. data.append("password", password);
  33. setTextModal(( typeof(await SendForm('login', data))==='string')? (await SendForm('login', data)) : '');
  34. }
  35. return <>
  36. <form onSubmit={postForm} className="authorization container align-items-center justify-content-center vw-100 vh-100 d-flex">
  37. <div className="col-4">
  38. <h4 className="w-100 text-center">Login</h4>
  39. <hr/>
  40. <label className="form-label">*Username</label><br/>
  41. <input type="text" id="username" className='input form-control mb-3' value={login} onChange={e => setLogin(e.target.value)}/>
  42. <label className="form-label">*Password</label>
  43. <input type="password" id="password" className='form-control mb-3' value={password} onChange={e => setPassword(e.target.value)}/>
  44. <p className='text-danger'>{textModal ? ('*' + textModal) : ''}</p>
  45. <div className="d-flex justify-content-between">
  46. <Link to="/register" className="">Register</Link>
  47. <button type='submit' className="btn btn-outline-danger" disabled={ password.length < 8 || login.length < 5} onClick={() => console.log(textModal)}>Log in</button>
  48. </div>
  49. </div>
  50. </form>
  51. </>
  52. }
  53. //export const CLoginForm = connect(state => ({ authState: state.auth?.token }))(LoginForm);