Skip to content

Instantly share code, notes, and snippets.

@medhruv7
Last active May 18, 2020 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save medhruv7/81ae9f8382a24663f12ce4c4dfeffbcd to your computer and use it in GitHub Desktop.
Save medhruv7/81ae9f8382a24663f12ce4c4dfeffbcd to your computer and use it in GitHub Desktop.
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