import React, { Component } from 'react';
import './App.css';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import { Link, Redirect, Switch } from 'react-router-dom';
import Axios from 'axios';
const styles = {
root: {
backgroundColor: '#1262e2',
color: 'white',
},
grow: {
flexGrow: 1,
},
form: {
marginTop: '5em',
color: 'Black',
backgroundColor: 'white',
width: 550,
height: 350,
borderRadius: 5,
},
input: {
width: 300,
color: 'white',
marginTop: '1em',
marginBottom: '0.5em',
}
};
class LoginForm extends Component {
constructor(props) {
super(props);
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
username: '',
password: '',
authenticated: false,
};
}
componentDidMount() {
fetch('/users/authenticated')
.then(res => res.text())
.then(
(res) => {
if(res === 'true') {
this.setState({authenticated: true});
} else {
this.setState({authenticated: false});
}
}
)
.catch(err => console.log(err));
}
onChangeUsername = (e) => {
this.setState({username: e.target.value});
};
onChangePassword = (e) => {
this.setState({password: e.target.value});
};
onSubmit(e) {
const params = {
username: this.state.username,
password: this.state.password
};
Axios.post('/users/login', params).then((res) => {
if(res.status === 200) {
this.setState({ authenticated: true });
}
}).catch((err) => {
console.log(err);
});
e.preventDefault();
};
render() {
const { authenticated } = this.state;
if(authenticated === true) {
return (authenticated === true ? <div><p className="redirect">Redirecting you...</p><Redirect to= '/income' /></div>: <p>Oops</p>);
} else {
return(
<div>
<form className={this.props.classes.form} onSubmit={this.onSubmit}>
<Typography variant="h5" color="inherit">Login</Typography>
<TextField
name="username"
label="Enter Your Username"
required
autoFocus
className={this.props.classes.input}
variant="outlined"
value={this.state.username}
onChange={this.onChangeUsername}
/>
<TextField
label="Enter Your Password"
className={this.props.classes.input}
variant="outlined"
type="password"
value={this.state.password}
onChange={this.onChangePassword}
/>
<div className="form-group">
<Button variant="contained" className={this.props.classes.root} type="submit">Login</Button>
</div>
<Switch>
<Link to='/register'>Not Signed Up? Click Here to Register...</Link>
</Switch>
</form>
</div>
)
}
}
}
export default withStyles(styles)(LoginForm);
Comments