|
| 1 | +import React from "react"; |
| 2 | +import TaskForm from "./TaskForm"; |
| 3 | +import TaskList from "./TaskList"; |
| 4 | +import request from 'superagent'; |
| 5 | + |
| 6 | +export default class TaskApp extends React.Component { |
| 7 | + constructor(props) { |
| 8 | + super(props); |
| 9 | + this.state = { |
| 10 | + data: [] |
| 11 | + }; |
| 12 | + } |
| 13 | + |
| 14 | + loadTaskFromServer() { |
| 15 | + request |
| 16 | + .get(this.props.url) |
| 17 | + .accept('application/json') |
| 18 | + .end((err, res) => { |
| 19 | + if (err || !res.ok) { |
| 20 | + console.error(this.props.url, |
| 21 | + status, err.toString()); |
| 22 | + } else { |
| 23 | + this.setState({data: res.body}); |
| 24 | + } |
| 25 | + }); |
| 26 | + } |
| 27 | + |
| 28 | + handleTaskSubmit(task) { |
| 29 | + var tasks = this.state.data; |
| 30 | + var newTasks = tasks.concat([task]); |
| 31 | + this.setState({data: newTasks}); |
| 32 | + request |
| 33 | + .post(this.props.url) |
| 34 | + .accept('application/json') |
| 35 | + .send({task: task}) |
| 36 | + .end((err, res) => { |
| 37 | + if (err || !res.ok) { |
| 38 | + console.error(this.props.url, |
| 39 | + status, err.toString()); |
| 40 | + } else { |
| 41 | + this.setState({data: newTasks}); |
| 42 | + } |
| 43 | + }); |
| 44 | + } |
| 45 | + |
| 46 | + taskUpdate(task) { |
| 47 | + request |
| 48 | + .patch(this.props.url + '/' + task.task.id) |
| 49 | + .accept('application/json') |
| 50 | + .send(task) |
| 51 | + .end((err, res) => { |
| 52 | + if (err || !res.ok) { |
| 53 | + console.error(this.props.url, status, err.toString()); |
| 54 | + } else { |
| 55 | + this.setState({data: res.body}); |
| 56 | + } |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + componentDidMount() { |
| 61 | + this.loadTaskFromServer(); |
| 62 | + setInterval(this.loadTaskFromServer.bind(this), |
| 63 | + this.props.pollInterval); |
| 64 | + } |
| 65 | + |
| 66 | + render() { |
| 67 | + return ( |
| 68 | + <div className="TaskApp"> |
| 69 | + <TaskForm |
| 70 | + onTaskSubmit={this.handleTaskSubmit.bind(this)} /> |
| 71 | + <table className="table table-striped"> |
| 72 | + <thead> |
| 73 | + <tr> |
| 74 | + <th>Content</th> |
| 75 | + <th>Status</th> |
| 76 | + <th colSpan="3"></th> |
| 77 | + </tr> |
| 78 | + </thead> |
| 79 | + <TaskList data={this.state.data} onTaskUpdate={this.taskUpdate.bind(this)} /> |
| 80 | + </table> |
| 81 | + </div> |
| 82 | + ); |
| 83 | + } |
| 84 | +} |
0 commit comments