Created
April 30, 2020 22:58
-
-
Save viniciusdacal/d07a646fea6604d317941977035065d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useContext } from 'react'; | |
import { useHistory, useLocation } from 'react-router-dom'; | |
import StoreContext from 'components/Store/Context'; | |
import UIButton from 'components/UI/Button/Button'; | |
import './Login.css'; | |
function initialState() { | |
return { user: '', password: '' }; | |
} | |
function login({ user, password }) { | |
if (user === 'admin' && password === 'admin') { | |
return { token: '1234' }; | |
} | |
return { error: 'Usuário ou senha inválido' }; | |
} | |
const UserLogin = () => { | |
const [values, setValues] = useState(initialState); | |
const [error, setError] = useState(null); | |
const { setToken } = useContext(StoreContext); | |
const history = useHistory(); | |
const location = useLocation(); | |
function onChange(event) { | |
const { value, name } = event.target; | |
setValues({ | |
...values, | |
[name]: value | |
}); | |
} | |
function onSubmit(event) { | |
event.preventDefault(); | |
const { token, error } = login(values); | |
if (token) { | |
setToken(token); | |
if (location?.state.redirectOnAuthenticated) { | |
return history.push(location.state.from); | |
} | |
return history.push('/'); | |
} | |
setError(error); | |
setValues(initialState); | |
} | |
return ( | |
<div className="user-login"> | |
<h1 className="user-login__title">Acessar o Sistema</h1> | |
<form onSubmit={onSubmit}> | |
<div className="user-login__form-control"> | |
<label htmlFor="user">Usuário</label> | |
<input | |
id="user" | |
type="text" | |
name="user" | |
onChange={onChange} | |
value={values.user} | |
/> | |
</div> | |
<div className="user-login__form-control"> | |
<label htmlFor="password">Senha</label> | |
<input | |
id="password" | |
type="password" | |
name="password" | |
onChange={onChange} | |
value={values.password} | |
/> | |
</div> | |
{error && ( | |
<div className="user-login__error">{error}</div> | |
)} | |
<UIButton | |
type="submit" | |
theme="contained-green" | |
className="user-login__submit-button" | |
rounded | |
> | |
Entrar | |
</UIButton> | |
</form> | |
</div> | |
); | |
}; | |
export default UserLogin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment