-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
92 lines (79 loc) · 2.22 KB
/
index.js
File metadata and controls
92 lines (79 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import MovementList from './components/MovementList/MovementList'
import AccountList from './components/AccountList/AccountList'
import AccountForm from './components/AccountForm/AccountForm'
import Loading from './components/Loading/Loading'
import LoginForm from './components/LoginForm/LoginForm'
import FinancialAxios from './utils/FinancialAxios'
import AuthenticatedRequest from './utils/AuthenticatedRequest'
class App extends Component {
state = {
loading: false,
accounts: [],
user: {},
token: null,
}
render() {
if (this.state.loading) {
return <Loading />;
}
if (!this.currentUser()) {
return <LoginForm login={this.login} />
}
return (
<div className='account-container'>
<button onClick={this.onClickLogout}>Logout</button>
<AccountForm onCreate={this.buildAccount} />
<AccountList data={this.state.accounts} />
</div>
);
}
buildAccount = (name, config) => {
// { name: name }
FinancialAxios.post('accounts', { name, user_id: 1 })
.then(response => {
// Spread operator, destruir una estructura de datos en su mínima expresión.
this.setState({
accounts: [...this.state.accounts, response.data]
});
config.onSuccess();
})
.catch(error => {
config.onError();
})
}
login = (email, password, config) => {
FinancialAxios
.post('session/login', { email, password })
.then(response => {
const { user, token } = response.data;
this.setState({ user, token, loading: true });
config.onSuccess();
this.fetchAccounts();
})
.catch(error => {
config.onError();
})
}
logout = () => {
this.setState({ user: {}, token: null })
}
onClickLogout = (event) => {
this.logout()
}
fetchAccounts() {
AuthenticatedRequest(this.state.token)
.get('accounts')
.then(response => {
this.setState({ accounts: response.data, loading: false });
})
}
currentUser() {
if (this.state.token) {
return this.state.user;
}
return false;
}
}
ReactDOM.render(<App />, document.getElementById('app'));