-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTodoApp.jsx
121 lines (112 loc) · 2.83 KB
/
TodoApp.jsx
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import React from 'react';
import { doers, todos } from '../../api/data';
import DoerInfo from './DoerInfo';
import AddTodo from './AddTodo';
import TodoList from './TodoList';
const DOERS = {};
export default class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {
todos: [],
doer: null,
errMsg: null,
};
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.addTodo = this.addTodo.bind(this);
this.markTodo = this.markTodo.bind(this);
this.deleteTodo = this.deleteTodo.bind(this);
for (const x of doers) {
DOERS[x.uid] = x;
}
}
componentDidMount() {
this.setState({ todos: [...todos] });
// fetch('/api/data.json')
// .then(x => x.json())
// .then((data) => {
// const todos = data.todos;
// this.setState({ todos });
// })
// .catch((e) => {
// console.warn(e);
// this.setState({ todos: [...todos] });
// });
}
login(name, pswd) {
if (!name || !pswd) {
this.setState({ errMsg: 'where is your password' });
return;
}
let doer = null;
for (const x in DOERS) {
if (DOERS[x].name === name) {
doer = DOERS[x];
break;
}
}
if (!doer) {
doer = { name, pswd };
const uids = Object.keys(DOERS);
doer.uid = uids[uids.length - 1].uid + 1;
DOERS[doer.uid] = doer;
this.setState({ doer, errMsg: '' });
return;
}
if (doer.pswd === pswd) {
this.setState({ doer, errMsg: '' });
} else {
this.setState({ errMsg: 'password do not match' });
}
}
logout() {
this.setState({ doer: null });
}
addTodo(content) {
const doer = this.state.doer || DOERS[0];
const todos = [...this.state.todos];
const tid = todos.length === 0
? 0
: todos[todos.length - 1].tid + 1;
const todo = { uid: doer.uid, done: false, tid, content };
todos.push(todo);
this.setState({ todos });
}
markTodo(tid) {
let todos = [...this.state.todos];
todos = todos.map((x) => {
if (x.tid !== tid) return x;
return { ...x, done: !x.done };
});
this.setState({ todos });
}
deleteTodo(tid) {
let todos = [...this.state.todos];
todos = todos.filter(x => x.tid !== tid);
this.setState({ todos });
}
render() {
const todos = [...this.state.todos];
const { doer, errMsg } = this.state;
return (
<div>
<h1>Todo List</h1>
<DoerInfo
doer={doer}
errMsg={errMsg}
login={this.login}
logout={this.logout}
/>
<AddTodo addTodo={this.addTodo} />
<hr />
<TodoList
todos={todos}
doers={DOERS}
markTodo={this.markTodo}
deleteTodo={this.deleteTodo}
/>
</div>
);
}
}