Last active
May 18, 2020 19:23
-
-
Save medhruv7/81ae9f8382a24663f12ce4c4dfeffbcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class TodoList extends React.Component { | |
constructor(props) { | |
super(props); | |
this.addTodo = this.addTodo.bind(this); | |
this.handleNewTaskInput = this.handleNewTaskInput.bind(this); | |
this.handleNewTaskSubmit = this.handleNewTaskSubmit.bind(this); | |
this.state = { | |
isLogged: this.props.isLogged, | |
userInfo : this.props.userInfo, | |
addingTask : false, | |
newTask : "" | |
} | |
} | |
addTodo(){ | |
this.setState({addingTask : true}); | |
} | |
handleNewTaskInput(e){ | |
this.setState({newTask : e.target.value}) | |
} | |
handleNewTaskSubmit(e){ | |
// firstly change the state of the UI then update | |
const len = this.state.userInfo.tasks.length | |
this.setState(prevState => ({ | |
...prevState, | |
tasks : [...prevState.userInfo.tasks,{task_key : len + 1,task : prevState.newTask}] | |
}), () => { | |
console.log(this.state) | |
// now make fetch call | |
const url = "http://localhost:4000/addItem"; | |
const req = { | |
newTask : this.state.newTask, | |
user_id : this.props.userInfo._id, | |
task_key : len + 1 | |
} | |
fetch(url,{ | |
method : 'POST', | |
body : JSON.stringify(req) | |
}).then((res) => res.json()).then((data) => console.log(data)) | |
}) | |
e.preventDefault(); | |
} | |
render() { | |
// console.log(this.state) | |
return ( | |
<div> | |
<button onClick = {this.addTodo}>Add More Tasks</button> | |
{this.state.addingTask && | |
<div> | |
<input type="text" placeholder="Enter the New task to be executed" value={this.state.newTask} onChange={this.handleNewTaskInput}/> | |
<button onClick={this.handleNewTaskSubmit}>Add</button> | |
</div> | |
} | |
<ol> | |
{this.state.userInfo.tasks.map((task) => | |
<li key={task.task_key}> | |
{task.task} | |
</li> | |
)} | |
</ol> | |
</div> | |
) | |
} | |
} | |
export default TodoList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment