authorization.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. 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. store.dispatch(actionAuthLogin(data.token, data.user));
  15. //console.log(history)
  16. history.push('/user');
  17. return data
  18. } else {
  19. return data.message;
  20. }
  21. })
  22. console.log(error)
  23. return error;
  24. }
  25. export const LoginForm = ({authState}) => {
  26. const [login, setLogin] = useState('');
  27. const [password, setPassword] = useState('');
  28. const [textModal, setTextModal] = useState('');
  29. const postForm = async(event) =>{
  30. event.preventDefault();
  31. const data = new FormData();
  32. data.append("login", login);
  33. data.append("password", password);
  34. setTextModal(( typeof(await SendForm('login', data))==='string')? (await SendForm('login', data)) : '');
  35. }
  36. return <>
  37. <form onSubmit={postForm} className="authorization container align-items-center justify-content-center vw-100 vh-100 d-flex">
  38. <div className="col-4">
  39. <h4 className="w-100 text-center">Login</h4>
  40. <hr/>
  41. <label className="form-label">*Username</label><br/>
  42. <input type="text" id="username" className='input form-control mb-3' value={login} onChange={e => setLogin(e.target.value)}/>
  43. <label className="form-label">*Password</label>
  44. <input type="password" id="password" className='form-control mb-3' value={password} onChange={e => setPassword(e.target.value)}/>
  45. <p className='text-danger'>{textModal ? ('*' + textModal) : ''}</p>
  46. <div className="d-flex justify-content-between">
  47. <Link to="/register" className="">Register</Link>
  48. <button type='submit' className="btn btn-outline-danger" disabled={ password.length < 8 || login.length < 5} onClick={() => console.log(textModal)}>Log in</button>
  49. </div>
  50. </div>
  51. </form>
  52. </>
  53. }
  54. export const CLoginForm = connect(state => ({ authState: state.auth?.token }))(LoginForm);