Deleting will work similarly to creating todos, with regard to passing state through props.
- Update the
Todo
component to contain a UI element to delete a todo.
// src/components/Todo.js
//...
class Todo extends Component {
render(){
return(
<p data-todos-index={this.props.todo._id}>
<span>{this.props.todo.body}</span>
<span
className='deleteButton'
onClick={() => this.props.onDeleteTodo(this.props.todo)}>
(X)
</span>
</p>
)
}
}
-
When the
span
with theX
gets clicked, it callsthis.props.onDeleteTodo
. The parent component ofTodo
will need to pass.onDeleteTodo
into theTodo
component. Briefly consider -- what is the parent component ofTodo
? -
In the
TodoList
class, sendthis.props.onDeleteTodo
to eachTodo
component that rendered by the list.
// src/components/TodoList.js
// ...
class TodoList extends Component {
render(){
let todoArray = this.props.todos.map( (todo) => {
return (
<Todo
key={todo._id}
todo={todo}
onDeleteTodo={this.props.onDeleteTodo} />
)
})
// ...
- One level further up, in the
TodoContainer
class, create adeleteTodo
method and pass it into theTodoList
component.
// src/containers/TodosContainer.js
// ...
deleteTodo(todo){
console.log('deleting todo', todo)
}
render(){
return (
<div className='todosContainer'>
<CreateTodoForm
createTodo={this.createTodo.bind(this)} />
<TodoList
todos={this.state.todos}
onDeleteTodo={this.deleteTodo.bind(this)} />
</div>
)
}
- Instead of logging a message to the console, the
deleteTodo
method should trigger an AJAX call. There's no method for that in the model yet, though. Add adelete
static method to theTodoModel
class that makes this request.
// src/models/Todo.js
// ...
static delete(todo){
let request = $.ajax({
url: `https://super-crud.herokuapp.com/todos/${todo._id}`,
method: 'DELETE'
})
return request
}
- Fill in the
deleteTodo
method ofTodosContainer
so that it uses theTodoModel.delete
method to make an AJAX call to the super-crud API and delete the correct todo.
deleteTodo(todo) {
console.log('deleting todo', todo)
TodoModel.delete(todo).then((res) => {
let todos = this.state.todos.filter(function(todo) {
return todo._id !== res._id
});
this.setState({todos})
})
}
- Think critically about the code for the delete feature. In your own words, explain how the
Todo
component class'sonDeleteTodo
method works.
click
The onDeleteTodo
function calls the deleteTodo
method from the todo component's props
. This method is actually a method from TodoList
. It takes the todo, passed as the function's argument from the child component, up through a chain of references. It deletes the todo with an AJAX call through TodoModel
's static delete
method.
After the TodoModel.delete
method finishes, back in TodosContainer
, all todos are grabbed from the container state. Then, the filter creates a new array that doesn't have the todo that was deleted. Finally, the method updates the state to have only the remaining todos.