-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTodoList.js
59 lines (50 loc) · 1.35 KB
/
TodoList.js
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
import React, { Component } from 'react';
import axios from 'axios';
import Task from './Task';
const apiUrl = 'https://api.tuture.co';
class ToDoList extends Component {
state = {
tasks: [],
newTask: '',
};
componentDidMount() {
return axios
.get(`${apiUrl}/tasks`)
.then((tasksResponse) => {
this.setState({ tasks: tasksResponse.data });
})
.catch((error) => console.log(error));
}
addATask = () => {
const { newTask, tasks } = this.state;
if (newTask) {
return axios
.post(`${apiUrl}/tasks`, { task: newTask })
.then((taskResponse) => {
const newTasksArray = [...tasks];
newTasksArray.push(taskResponse.data.task);
this.setState({ tasks: newTasksArray, newTask: '' });
})
.catch((error) => console.log(error));
}
};
handleInputChange = (event) => {
this.setState({ newTask: event.target.value });
};
render() {
const { newTask } = this.state;
return (
<div>
<h1>ToDoList</h1>
<input onChange={this.handleInputChange} value={newTask} />
<button onClick={this.addATask}>Add a task</button>
<ul>
{this.state.tasks.map((task) => (
<Task key={task.id} id={task.id} name={task.name} />
))}
</ul>
</div>
);
}
}
export default ToDoList;