1
0
mirror of https://github.com/franjsco/tick3t synced 2025-06-05 22:19:18 +02:00

refactor: Login component

This commit is contained in:
Francesco Esposito
2019-07-31 16:10:18 +02:00
parent a9fef41cfb
commit fa610280e0

View File

@@ -1,5 +1,7 @@
import React, { Component } from 'react'; import React, { Component } from 'react';
import { Link, Redirect } from 'react-router-dom'; import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../../_actions';
import { import {
Row, Row,
Col, Col,
@@ -9,8 +11,6 @@ import {
Input Input
} from 'reactstrap'; } from 'reactstrap';
import { login } from '../../api/authentication';
import Card from '../../components/Card'; import Card from '../../components/Card';
import Button from '../../components/Button'; import Button from '../../components/Button';
@@ -44,49 +44,29 @@ class Login extends Component {
const { email, password } = this.state; const { email, password } = this.state;
login(email, password) this.props.login(email, password);
.then((json) => {
if (!json.success) {
this.setState({
error: json.message
});
} else {
localStorage.setItem('user', JSON.stringify(json.data));
this.setState({
success: true
});
}
})
.catch((err) => {
this.setState({
error: err.message
});
});
} }
resetLogin(event) { resetLogin(event) {
event.preventDefault(); event.preventDefault();
this.setState({ this.props.reset();
email: null,
password: null,
error: null
});
} }
render() { render() {
if (this.state.error) { if (this.props.error) {
return ( return (
<Card <Card
title="Error" title="Error"
> >
<p>{this.state.error}</p> <p>{this.props.error}</p>
<a href="" onClick={this.resetLogin}>Back to login</a> <a href="/" onClick={this.resetLogin}>Back to login</a>
</Card> </Card>
); );
} }
if (this.state.success) { if (this.props.loggedIn) {
return ( return (
<Redirect to="/admin/" /> <Redirect to="/admin/" />
) )
@@ -146,4 +126,18 @@ class Login extends Component {
} }
} }
export default Login; const mapStateToProps = (state) => {
return {
loggedIn: state.user.loggedIn,
error: state.user.error
};
}
const mapDispatchToProps = (dispatch) => {
return {
login: (email, password) => dispatch(userActions.login(email, password)),
reset: () => dispatch(userActions.reset())
};
}
export default connect(mapStateToProps, mapDispatchToProps) (Login);